mysql得到的顺序发生在group by之前

时间:2010-11-08 16:33:25

标签: sql mysql group-by sql-order-by

我有三张桌子,我只会在这里向您展示相关栏目

  

表:组列:group_id,name。

     

表:groups_to_message列:   group_id,message_id

     

表:消息列:message_id,   创建(日期)

我需要基本上找到每个组的最后一条消息,而不显示重复的组。

我尝试过像这样使用group:

SELECT m.created, g.group_id 
FROM groupss as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m 
GROUP BY g.group_id 
ORDER BY m.created DESC

这会导致成功分组,但是在ORDER BY之前完成,因此在排序之前会先获得第一个结果。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:3)

如果我正确地阅读你的问题,请使用MAX()。这应该可以获得每个组的最新项目

示例...

SELECT MAX(m.created), g.group_id 
FROM groupss as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m ON (gm.message_id = gm.message_id)
GROUP BY g.group_id 
ORDER BY m.created DESC

答案 1 :(得分:0)

SELECT  m.created, g.group_id
FROM    groupss g
JOIN    messages m
ON      m.id = 
        (
        SELECT  mi.id
        FROM    group_to_message gm
        JOIN    message mi
        ON      mi.message_id = gm.message_id
        WHERE   gm.group_id = g.group_id
        ORDER BY
                gm.group_id DESC, mi.created DESC
        LIMIT 1
        )

答案 2 :(得分:0)

这是未经测试的,但它应该有效:

SELECT m.created, g.group_id 
FROM groups as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m ON (gm.message_id = m.id)
GROUP BY g.group_id HAVING m.created = MAX(m.created)