I got two tables.
A dealer table (id, name, etc.) and an event table (id, did(dealerid), eid(fb eventid), venue, etc.) where I save the dealerid, eventid, eventurl and date from facebook.
I can get all data with this sql statement:
SELECT * FROM dealer as t_d INNER JOIN events AS t_e
ON t_d.id = t_e.did;
This works fine.
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
As you can see, I get two rows for the dealer id 2, because there are two events listed.
How can I get the event, which is the closest to this date (today).
Later, there will be like 20 Dealer and for each one at least 3-4 events.
A hint would be nice, thank you!
UPDATE:
This is the solution!
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
But is it somehow possible to display ALL dealers, even if no event exists for the dealer?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.