1

这适用于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

谁能解释我为什么?

4

1 回答 1

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

于 2012-12-14T14:27:35.483 回答