2014-06-30 64 views
0

我有一些表與一對多的關係,我需要加入最近到父。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列日期獲取最近的行?

+0

您是否考慮過將日期存儲爲['DATE'](http://dev.mysql.com/doc/refman/5.1/en/datetime.html)? –

回答

0

當你定義p1時,你可以做CONCAT嗎?

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) 
+0

我設法解決它,但我做了稍微不同,但它是基本相同的想法。我在連接中執行了「CONCAT」,它工作正常! – Adam

+0

@Adam你的意思是在'ON'子句中? – Dan

+1

是的,沒錯 – Adam