加入两个表并应用分组,但更改排序顺序

时间:2018-03-28 15:42:27

标签: mysql join group-by versioning

我有两个表,事件和版本。一个事件有很多版本。我想执行内部联接并为每个事件获取最新版本。

QUERY

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

表事件

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

表格版本

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

实际结果(内连接和分组后)

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

期望的结果

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

按顺序排序结果是,但我需要的行首先不在那里。我需要什么查询?谢谢!

1 个答案:

答案 0 :(得分:0)

在子查询中获取每个事件的最大版本。然后将表连接到子查询结果:

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