mysql加入四个表并按desc计数结果顺序

时间:2018-08-18 13:24:31

标签: mysql

我正在使用Mysql来获取热门帖子

我将加入四个表postslike,posts_shares,posts_shares,posts_comments,并区分其中的user_id。 (应该添加帖子,分享和评论的总数)

我希望得到这样的结果

RESULT:
post_id | user_id | count of shares, like, comments
---------------------------------------------------
  1     |     2    |      50                      |
  8     |     5    |      47                      |
---------------------------------------------------

表结构

table users
---------------------
id | username | etc |
---------------------

table posts
-------------------------------------
id |  user_id | content | datecreated
-------------------------------------

post_likes
--------------------------------
id | post_id | user_id         |
--------------------------------

post_shares
--------------------------------
id | post_id | user_id         |
--------------------------------

comments
---------------------------------------
id | post_id | user_id | description  |
--------------------------------------

user_id应该是不同的

2 个答案:

答案 0 :(得分:1)

您可以使用左联接,并按p.id,p.user_id,u.username计数不同的分组

select p.id as post_id, p.user_id, u.username
    , count(distinct l.user_id)
    , count(distinct s.user_id)
    , count(distinct c.user_id)
    , ifnull(count(distinct l.user_id),0) + 
      ifnull(count(distinct s.user_id),0) + 
      ifnull(count(distinct c.user_id),0) total
from post p 
inner join users u  on u.id = p.user_id 
left join post_likes l on l.post_id = p.id 
left join post_shares s on s.post_id = p.id  
left join comments c on c.post_id = p.id 
group by  p.id, p.user_id, u.username
order by total desc 

答案 1 :(得分:0)

要获取count of shares, like, comments,建议您在这三个表上使用UNION

类似(请检查语法):

SELECT post_id, user_id, count(post_id) From (
SELECT post_id, user_id FROM post_likes
UNION
SELECT post_id, user_id FROM post_shares
UNION
SELECT post_id, user_id FROM comments) Group by post_id, user_id