2011-02-24 40 views
0

我试图运行此查询:MySQL的更新内加入别名

UPDATE anothertable 
INNER JOIN (SELECT *, 
        LEAST(table1.from_price, table2.from_price, table3.from_price) AS cheapestPrice 
       FROM (SELECT * FROM table1 v WHERE hotelid >= 1 
        UNION 
        SELECT * FROM table2 c WHERE hotelid >= 1 
        UNION 
        SELECT * FROM table3 k WHERE hotelid >= 1) AS temp  
      GROUP BY temp.hotelid, temp.country) AS i ON anothertable.id = i.hotelid 
                AND anothertable.country = i.country 
SET price = i.cheapestPrice, 
    op = i.to 

但是我不能让LEAST函数可以访问一个名为“from_price”字段。

想法?

回答

2

您应该使用最少的,而不是最:

Update anothertable 
    Join (
      Select hotelid, country, to 
       , Min(from_price) AS cheapestPrice 
      From (
        Select hotelid, country, from_price, to 
        From table1 v 
        Where hotelid >= 1 
        Union 
        Select hotelid, country, from_price, to 
        From table2 c 
        Where hotelid >= 1 
        Union 
        Select hotelid, country, from_price, to 
        From table3 k 
        Where hotelid >= 1 
        ) AS temp 
      Group By temp.hotelid, temp.country, temp.to 
      ) As i 
     On anothertable.id = i.hotelid 
      And anothertable.country = i.country 
Set price = i.cheapestPrice 
    , op = i.to 

编辑

正如在评论中指出,我忽略从内临时查询to列。但是,对我而言,现在还不清楚应该如何包含to,因为您在声明Group By列时使用了MySQL的一个可怕功能。我假设您需要将to包含在Group By中,但如果不是这种情况,则应该明确说明它应该在to列中使用的聚合函数。

这里有一个替代的,我用最少的to列:

Update anothertable 
    Join (
      Select temp.hotelid, temp.country 
       , Min(temp.to) As to 
       , Min(temp.from_price) AS cheapestPrice 
      From (
        Select v.hotelid, v.country, v.from_price, v.to 
        From table1 v 
        Where hotelid >= 1 
        Union 
        Select c.hotelid, c.country, c.from_price, c.to 
        From table2 c 
        Where hotelid >= 1 
        Union 
        Select k.hotelid, k.country, k.from_price, k.to 
        From table3 k 
        Where hotelid >= 1 
        ) AS temp 
      Group By temp.hotelid, temp.country 
      ) As i 
     On anothertable.id = i.hotelid 
      And anothertable.country = i.country 
Set price = i.cheapestPrice 
    , op = i.to 
+0

'i.to'在缺少quert – RichardTheKiwi 2011-02-24 18:12:22

+0

@Richard又名cyberkiwi - 你的意思是不是最后一行其他? – Thomas 2011-02-24 18:24:23

+0

我的意思是你的查询会因为它而失败。它指什么 – RichardTheKiwi 2011-02-24 18:25:21