我有一些表與一對多的關係,我需要加入最近到父。SQL加入使用動態別名列
我遇到的問題是日期存儲爲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列日期獲取最近的行?
您是否考慮過將日期存儲爲['DATE'](http://dev.mysql.com/doc/refman/5.1/en/datetime.html)? –