有 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
最佳答案
您不需要在 group by 之前添加 order by ,使用 group by 返回的结果是不确定的,这不能保证您提供该帖子的最新聊天记录,但这里是您可以做到这一点的方法,使用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
因此您会看到重复的列名称错误,要解决此问题,您需要为其中一个列提供不同的别名
关于mysql - 分组依据之前排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549649/