简体   繁体   English

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

[英]get count(*) from multiple tables sql

I have three tables. 我有三张桌子。

entry 条目

ID   title
1    Entry1
2    Entry2
3    Entry3
4    Entry4

user_likes user_likes

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

user_bookmarks user_bookmarks

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

What i want is the sum of likes and bookmarks for each entry. 我想要的是每个条目的喜欢和书签的总和。

result 结果

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

Also with total sum of likes and bookmarks of each entry. 还包含每个条目的喜欢和书签的总和。

result2 RESULT2

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

I managed to get likes and bookmark result using this query in seperate tables. 我在单独的表格中使用此查询设法获得了喜欢和书签结果。 I was not able to show them together in a single table. 我无法在一张桌子上一起显示它们。

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

You should aggregate before joining: 加入之前,您应该先进行汇总:

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;

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

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