简体   繁体   English

为同一列的两个不同表合并mysql count(*)

[英]Combine mysql count(*) for two different tables same column

I have two tables that store comments from two different users 我有两个表,用于存储来自两个不同用户的评论

Table1

id_table1 | comment | id_user | id_post

Table2

id_table2 | comment | id_someOtherUser | id_post

I would really like to make only one table out of this two because comments are posted on the same post, but i can't because i have two different id's for two different kind of users. 我真的很想在这两个表中只做一张表,因为评论是发布在同一帖子上的,但是我不能,因为我为两种不同类型的用户有两个不同的ID。

My question is how can i list all posts DESC by number of comments combined from two tables? 我的问题是如何按两个表中合并的评论数列出所有DESC?

If i do something like 如果我做类似的事情

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

Then i have posts for table1, same can be done for table2, but how can i combine comments from both tables for the same post? 然后我有针对table1的帖子,可以针对table2进行相同的操作,但是如何将两个表格的评论合并为同一帖子?

I would use UNION ALL to combine the two comment tables in a common format, then do the JOIN : 我将使用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

解决此问题的一种方法是对每个表进行单独的计数,然后执行完全外部联接,并取每个计数的总和:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM