简体   繁体   English

SQL-从表中获取最新事件

[英]SQL - Get the latest event from table

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. 经销商表(id,名称等)和事件表(id,did(dealerid),eid(fb eventid),场所等),我从Facebook保存了Dealerid,eventid,eventurl和日期。

I can get all data with this sql statement: 我可以使用以下sql语句获取所有数据:

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. 如您所见,由于有两个事件,我得到了两行作为经销商ID 2的信息。
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. 以后,将有20个发牌人,每一个至少有3-4个事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM