我有两张桌子 经销商表(id,名称等)和事件表(id,did(dealerid),eid(fb eventid),场地等),我从facebook保存dealerid,eventid,eventurl和date。
我可以使用这个sql语句获取所有数据:
SELECT * FROM dealer as t_d INNER JOIN events AS t_e
ON t_d.id = t_e.did;
这很好用。
1 Laden Dortmund Stra 12 45525 Dortmund DE www.google.de 0201-123456 laden@dortmund.de 300 400 1 1 416364098428245 https://www.facebook.com/events/416364098428245/ 2013-01-28
2 Laden Unna Wurststr. 123 45130 Unna DE www.bing.de 0222-11223344 laden@unna.de 400 276 2 2 145457548940302 https://www.facebook.com/events/145457548940302/ 2013-03-08
2 Laden Unna Wurststr. 123 45130 Unna DE www.bing.de 0222-11223344 laden@unna.de 400 276 3 2 405092472902921 https://www.facebook.com/events/405092472902921/ 2013-04-26
如您所见,我为经销商ID 2获取了两行,因为列出了两个事件 我怎样才能得到最接近这个日期(今天)的活动。
稍后,将有20个经销商,每个至少3-4个事件。
提示会很好,谢谢!
更新
这是解决方案!
SELECT t_d.*, t_e.*, DATE_FORMAT(t_e.date,'%d.%m.%Y') as date
FROM dealer as t_d
INNER JOIN events AS t_e
ON t_d.id = t_e.did
INNER JOIN
(
SELECT did, MIN(date) minDate
FROM events
GROUP BY did
) e ON t_e.did = e.did AND
t_e.date = e.minDate
但是,即使经销商没有活动,是否有可能显示所有经销商?
答案 0 :(得分:5)
SELECT t_d.*, t_e.*
FROM dealer as t_d
INNER JOIN events AS t_e
ON t_d.id = t_e.did
INNER JOIN
(
SELECT did, MAX(date) maxDate
FROM events
GROUP BY did
) e ON t_e.did = e.did AND
t_e.date = e.maxDate