有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

最佳答案

您不需要在分组依据之前订购,使用分组依据返回的结果不确定,这不能保证您为帖子提供最新的聊天信息,但是这是您可以使用自我加入的方法聊天记录上的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,因此您看到重复的列名错误,要解决这个问题,您需要为该列提供不同的别名

09-11 17:18