Mysql 分组前排序
有两张桌子:混乱的聊天,混乱的帖子。我需要将它们组合在Mysql 分组前排序,mysql,sorting,group-by,Mysql,Sorting,Group By,有两张桌子:混乱的聊天,混乱的帖子。我需要将它们组合在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.
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\u posts.chatID
列名更改为mess\u 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 plus上的最长时间戳上使用自连接进行
mess\u 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
,因此您会看到重复的列名错误,要解决此问题,您需要为一列指定不同的别名
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