从多个表sql中获取count(*)

时间:2017-05-07 13:04:47

标签: mysql sql

我有三张桌子。

输入

ID   title
1    Entry1
2    Entry2
3    Entry3
4    Entry4

user_likes

ID   user_id    entry_id
1       1           3
2       3           1
3       9           4
4       2           2

user_bookmarks

ID   user_id    entry_id
1       6           3
2       4           3
3       2           1
4       2           2

我想要的是每个条目的喜欢和书签的总和。

结果

entryID   likes    bookmarks
   1        1          1
   2        1          1
   3        1          2
   4        1          0

还有每个条目的喜欢和书签的总和。

RESULT2

entryID   likes+bookmarks
   1            2
   2            2
   3            3
   4            1

我设法在单独的表中使用此查询获取喜欢和书签结果。我无法在一张桌子上一起展示它们。

SELECT entry.id, COUNT(entry.id) AS likes FROM entry 
INNER JOIN user_like ON user_like.entry_id = entry.id GROUP BY entry.id ORDER BY likes DESC

1 个答案:

答案 0 :(得分:2)

您应该在加入之前汇总

select e.*, coalesce(l.likes, 0) as likes,
       coalesce(b.bookmarks, 0) as bookmarks,
       (coalesce(l.likes, 0) + coalesce(b.bookmarks, 0)) as both
from entries e left join
     (select entryid, count(*) as likes
      from likes l
      group by entryid
     ) l
     on l.entryid = e.id left join
     (select entryid, count(*) as bookmarks
      from bookmarks
      group by entryid
     ) b
     on b.entryid = e.id;