想用max(日期)的行

时间:2012-12-14 14:19:50

标签: mysql

这适用于MYSQL:

SELECT hi_Historie_id, 
  hi_Klus_id, 
  hi_Datum_gedaan, 
  hi_Prijs, 
  hi_Voldaan, 
  hi_Datum_voldaan, 
  hi_Voldaan_via, 
  max(hi_next_date), 
  hi_Opmerking
FROM Historie 
GROUP BY hi_Klus_id

这会得到正确的结果: hi_Klus_id的最新日期的所有行。

但是我会与另一张桌子联系:

LEFT OUTER JOIN Glazenwassen ON Historie.hi_Klus_id = Glazenwassen.gw_Klus_id 
WHERE Historie.hi_next_date <= CURDATE()

这会产生错误#1064

有人能解释我为什么吗?

1 个答案:

答案 0 :(得分:0)

我的建议是创建一个子查询来返回MAX(hi_next_date),然后将该结果连接到HistorieGlazenwassen表:

select h.hi_Historie_id, 
  h.hi_Klus_id, 
  h.hi_Datum_gedaan, 
  h.hi_Prijs, 
  h.hi_Voldaan, 
  h.hi_Datum_voldaan, 
  h.hi_Voldaan_via, 
  h.hi_next_date, 
  h.hi_Opmerking
from Historie h
inner join
(
  select max(hi_next_date) hi_next_date, hi_Klus_id
  from Historie
  group by hi_Klus_id
) h2
  on h.hi_Klus_id = h2.hi_Klus_id
  and h.hi_next_date = h2.hi_next_date
left join Glazenwassen g
  on h.hi_Klus_id = g.gw_Klus_id
where h.hi_next_date <= CURDATE() 

当您将子查询加入Historie表格时,您需要同时加入hi_next_datehi_Klus_id