SQL连接使用动态别名列

时间:2014-06-30 09:33:09

标签: mysql sql join left-join alias

我有一些表与一对多的关系,我需要将最新的表加入到父表中。

我遇到的问题是日期存储为3列:日,月,年。这是因为如果用户不知道确切的日期,则该日期是可选字段。

要将完整日期作为一列我在SELECT语句中进行,但是MySQL告诉我我不能在ON子句中使用这些用于我的连接的这些列。

SELECT
    restaurants.*,
    locations.name AS location,
    files.filename AS flag,
    CONCAT(p1.open_year,'-',p1.open_month,'-',COALESCE(NULLIF(p1.open_day,''), '30')) AS open_date,
    CONCAT(p2.open_year,'-',p2.open_month,'-',COALESCE(NULLIF(p2.open_day,''), '30')) AS p2_open_date
FROM restaurants
    LEFT JOIN locations ON restaurants.location_id = locations.id
    LEFT JOIN files ON locations.flag_id = files.id
    LEFT JOIN projects p1 ON (restaurants.id = p1.restaurant_id)
    LEFT OUTER JOIN projects p2 ON (restaurants.id = p2.restaurant_id AND 
(open_date < p2_open_date OR open_date = p2_open_date AND p1.id < p2.id))
WHERE restaurants.$by = :search
GROUP BY restaurants.id

如何根据3列日期获取最新行?

1 个答案:

答案 0 :(得分:0)

您定义CONCAT时可以执行p1吗?

LEFT JOIN (SELECT
           --attributes you need from projects... 
           CONCAT(p1.open_year,'-',p1.open_month,'-',COALESCE(NULLIF(p1.open_day,''), '30')) AS open_date 
           FROM projects) p1 ON (restaurants.id = p1.restaurant_id)