2011-02-24 41 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