2012-08-17 40 views
0

我有fixedassetsfixedassets_history表。加入兩個表並獲取兩個表中的最新條目取決於MySQL中兩個表的更新日期

fixedassets表中,有id,purchase_date,purchase_price,updated_date

fixedassets_history表中有fixedassets_id,description,updated_date

我加入這些表id。我想根據fixedassetsupdate_date字段和fixedassets_historyupdated_date在MySQL中檢索這些表中最近更新的記錄。

這是我的SQL腳本:

SELECT fa.*,fh.text,fh.date 
FROM fixedassets fa 
JOIN fa_history fh ON fa.id=fh.fixedassets_id 
ORDER BY fa.updated_date desc,fh.date desc limit 5 

回答

0
select 
fa.id, 
max(fa.updated_date) , 
fa.other_column 
from fixedassets fa 
left join (
      select 
       fixedassets_id , 
       max(updated_date) , 
       other_columns 
       from fixedassets_history 
      ) as fah on fah.fixedassets_id = fa.id 
group by fa.id