MySQL更新内部加入别名

时间:2011-02-24 17:45:26

标签: mysql sql join sql-update

我正在尝试运行此查询:

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”的字段。

想法?

1 个答案:

答案 0 :(得分:2)

你应该使用Min而不是Least:

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但是如果不是这种情况,你应该明确它应该在to列上使用哪个聚合函数。

这是我在to列上使用Min的替代方案:

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