0

我有两张桌子。

带有列 ID、forumID、标题、内容、unixtime 的“threads”

带有列 ID、threadID、content、unixtime 的“comments”

我想做一个mysql查询,根据它们的unixtime对这两个表中的所有行进行排序,但也不显示相同的“threadID”两次。

以下查询将合并这两个表并对它们进行排序,但我无法删除重复的线程。我尝试了一些 GROUP BY 和 DISTINCT,但没有运气。

(SELECT unixtime, ID, threadID FROM comments)
UNION
(SELECT unixtime, ID, forumID FROM threads)
ORDER BY unixtime DESC

它用于显示论坛的首页,因此让同一个主题出现多次是没有意义的。

编辑:我想显示最新的评论和最新的线程。

4

3 回答 3

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?

于 2012-05-26T10:16:55.887 回答
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
于 2012-05-26T10:02:59.390 回答
0

这将帮助您获得唯一的 threadID

(SELECT forumID, ID, unixtime FROM threads)
UNION
(SELECT distinct(threadID), ID, max(unixtime) FROM comments GROUPBY threadID)
ORDER BY unixtime DESC
于 2012-05-26T10:11:30.897 回答