我有两张桌子。
“threads”包含列ID,forumID,标题,内容,unixtime
“comments”包含列ID,threadID,内容,unixtime
我想做一个mysql查询,它根据unixtime对这两个表中的所有行进行排序,但也没有两次显示相同的“threadID”。
以下查询将合并这两个表并对它们进行排序,但我无法删除线程的重复项。我尝试了一些GROUP BY和DISTINCT,但没有运气。
(SELECT unixtime, ID, threadID FROM comments)
UNION
(SELECT unixtime, ID, forumID FROM threads)
ORDER BY unixtime DESC
它用于显示论坛的首页,因此让同一个帖子出现不止一次是没有意义的。
编辑:我想展示最新评论和最新帖子。答案 0 :(得分:1)
SELECT unixtime, ID, type, type_id
FROM (( SELECT unixtime, ID, 'comment' AS type, threadID, forumID
FROM ( SELECT unixtime, ID, threadID
FROM comments
ORDER BY unixtime DESC) AS h
GROUP BY threadID)
UNION ALL
( SELECT unixtime, ID, 'thread', ID, forumID
FROM threads)
ORDER BY unixtime DESC) AS h2
GROUP BY threadID
ORDER BY unixtime DESC
我改变了一些东西。我假设您想知道它的论坛或主题ID是不是?
答案 1 :(得分:0)
如果您没有加入钥匙,可以轻松解决问题:
Select DISTINCT tbl.unixtime from
(
(SELECT unixtime, ID, threadID FROM comments)
UNION
(SELECT unixtime, ID, forumID FROM threads)
ORDER BY unixtime DESC))
As tbl
答案 2 :(得分:0)
这将帮助您获得唯一的threadID
(SELECT forumID, ID, unixtime FROM threads)
UNION
(SELECT distinct(threadID), ID, max(unixtime) FROM comments GROUPBY threadID)
ORDER BY unixtime DESC