Join two tables and apply group by, but change sort order

余生长醉 提交于 2019-12-25 01:33:28

问题


I have two tables, event and version. An event has many versions. I want to perform an inner join and get THE LAST version for each event.

QUERY

SELECT * FROM events.event e INNER JOIN events.version v ON (e.version_id = v.id) GROUP BY e.event_id

TABLE EVENT

id  event_id    version_id  updated
1   1           7           03/08/2018
2   2           8           06/06/2018
3   2           9           02/07/2018

TABLE VERSION

id      name            description         comments
7       Dinner          A fancy dinner Z    Comment Z
8       Breakfast       Fancy breakfast Y   Comment Y
9       Breakfast       Fancy breakfast X   Comment X

ACTUAL RESULT (After inner join and group by)

id(e) event_id  version_id  id(v) name      description          comments
1     1         7           7     Dinner    A fancy dinner Z     Z
2     2         8           8     Breakfast Fancy breakfast Y    Y

DESIRED RESULT

id(e) event_id  version_id  id(v) name      description          comments
1     1         7           7     Dinner    A fancy dinner Z     Z
2     2         9           9     Breakfast Fancy breakfast X    X

Order by sorts the result yes, but the row I need is not there in the first place. What query do I need for this? Thanks!


回答1:


Get the max version per event in a subquery. Then join the tables to the subquery result:

SELECT e.*, v.*
FROM (
    SELECT event_id, MAX(version_id) as version_id
    FROM events.event
    GROUP BY event_id
) mx
JOIN events.event e USING(event_id, version_id)
JOIN events.version v ON v.id = e.version_id


来源:https://stackoverflow.com/questions/49538793/join-two-tables-and-apply-group-by-but-change-sort-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!