在分组之前排序

时间:2014-05-08 18:23:13

标签: mysql sorting group-by

有2个表:mess_chats,mess_posts。我需要将它们合并到chatID列,然后按时间戳排序,以便最新的帖子位于顶部,最后按chatID分组。

这是我的代码:

SELECT * FROM (
  SELECT   mess_chats.*, mess_posts.*
  FROM     mess_chats INNER JOIN mess_posts
           ON mess_chats.chatID = mess_posts.chatID
  WHERE    mess_chats.membersID="1"
  ORDER BY mess_posts.timestamp DESC
) AS tt
GROUP BY tt.chatID

这是错误:

#1060 - Duplicate column name 'chatID'

编辑: 我找到了解决方案,首先我将mess_posts.chatID列名更改为mess_posts.pchatID,然后将sql代码更改为:

SELECT * FROM (
  SELECT   mess_chats.*, mess_posts.*
  FROM     mess_chats JOIN mess_posts
           ON mess_chats.chatID = mess_posts.pchatID
  WHERE    mess_chats.membersID="1"
  ORDER BY mess_posts.timestamp DESC
) AS tt
GROUP BY tt.pchatID

2 个答案:

答案 0 :(得分:0)

您在分组之前不需要订单,使用分组返回的结果是不确定的,这不能保证您为该帖子提供最近的聊天,但这是您可以的方式这样做,在chatid上使用mess_chats表的自联接加上最大时间戳

SELECT 
    c.*,
    p.* 
  FROM
    mess_chats c
    INNER JOIN 
    (SELECT chatID, MAX(`timestamp`) `timestamp` 
       FROM mess_chats GROUP BY chatID ) mc
      ON(c.chatID = mc.chatID AND c.`timestamp` = mc.`timestamp`)
    INNER JOIN mess_posts p 
      ON c.chatID = p.chatID 
  WHERE c.membersID = "1" 
  ORDER BY p.timestamp DESC

对于查询中的错误,我会说你在两个表中都有chatID列具有相同的名称,所以当你进行子选择时,你可以参考tt.chatID然后在结果中有两列chatID所以你看到重复的列名称错误,为此,你需要为列中的一个提供不同的别名

答案 1 :(得分:0)

试试这个

SELECT * FROM (
    SELECT   mess_chats.*, mess_posts.*, mess_posts.chatID as 'post_chatID'
    FROM     mess_chats INNER JOIN mess_posts
        ON mess_chats.chatID = mess_posts.chatID
    WHERE    mess_chats.membersID="1"
    ORDER BY mess_posts.timestamp DESC
) AS tt
GROUP BY tt.post_chatID