如何加入这些表来计算这些数?

时间:2017-07-14 11:57:31

标签: sql postgresql

我有4张桌子:

<div id="test">

类似可以引用答案或问题,但不能同时引用,因此一个外键将为空。

喜欢的表中的

user_id是放置之类的用户。

如何计算每个用户的问题和答案上的喜欢数量?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要对每个用户ID进行计数,这些用户ID可以通过答案和问题一起获得。

如果是这样,那么一种方法是:

select  coalesce(questions.user_id, answers.user_id) as liked_user_id, count(*) 
from likes
left join questions
on likes.question_id = questions.id
left join answers
on likes.answer_id = answers.id
group by liked_user_id

答案 1 :(得分:1)

一种方法使用union all

select 'questions' as which, count(*)
from questions q join
     likes l
     on l.question_id = q.id
where q.user_id = $user_id
union all
select 'answers' as which, count(*)
from answers a join
     likes l
     on l.answer_id = a.id
where a.user_id = $user_id;

编辑:

如果您想将所有用户的结果放在一行中,那么相关的子查询是一种非常简单的方法:

select u.*,
       (select count(*)
         from questions q join
              likes l
              on l.question_id = q.id
         where q.user_id = u.id
       ) as question_likes,
       (select count(*)
         from answers a join
              likes l
              on l.answer_id = a.id
         where a.user_id = u.id
       ) as answer_likes
from users u;