我有两个表来存储来自两个不同用户的评论
Table1
id_table1 | comment | id_user | id_post
Table2
id_table2 | comment | id_someOtherUser | id_post
我真的只想在这两个中只有一个表,因为评论发布在同一个帖子上,但我不能,因为我有两个不同类型的用户的两个不同的ID。
我的问题是如何根据两个表格中的评论数量列出所有帖子DESC?
如果我做的话
SELECT P.*, count(*) as count from Table1 AS T1
LEFT JOIN post AS P ON T1.id_post = P.id_post GROUP BY P.id_post ORDER BY count DESC
然后我有table1的帖子,同样可以为table2完成,但是如何将两个表中的注释组合在一起呢?
答案 0 :(得分:0)
我会使用UNION ALL
以通用格式合并两个评论表,然后执行JOIN
:
SELECT P.*, TC.count
FROM (
SELECT Ts.id_post, count(*) AS count
FROM (
SELECT id_post FROM Table1
UNION ALL
SELECT id_post FROM Table2
) AS Ts
GROUP BY Ts.id_post
) AS TC
LEFT JOIN post AS P ON TC.id_post = P.id_post
GROUP BY P.id_post
ORDER BY TC.count DESC
答案 1 :(得分:0)
解决此问题的一种方法是对每个表执行单独的计数,然后执行完整的外部联接,并获取每个计数的总和:
SELECT id_post, (count1 + count2) AS total_count FROM
(SELECT id_post, count(*) as count1 from Table1 AS T1
FULL OUTER JOIN
(SELECT id_post, count(*) as count2 from Table2 AS T2)
USING(id_post))
ORDER BY total_count DESC