2017-07-14 76 views
0

我有4個表:我怎樣才能加入這些表來得到這個數字?

users 
id int primary key 

questions 
id int primary key 
user_id int references users(id) 

answers 
id int primary key 
question_id references questions(id) 
user_id references users(id) 

likes 
id int primary key 
answer_id references answers(id) 
question_id references questions(id) 
check answer_id xor question_id 

一個像可以參考答案或問題,但不能同時這樣一個外鍵將是無效的。

user_id在喜歡的表格中是放置類似的用戶。

如何計算每個用戶的問題和答案上的喜歡數量?

+0

你正在尋找的每一個總的問題和答案,或列合併喜歡? – yanman1234

+0

合併....... –

回答

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; 
+0

美麗,但你傳遞user_id作爲參數,我想要的是每個用戶行保持總喜歡count的一行,所以我需要加入用戶。 –

+0

@ AhmadAl-kheat。 。 。這是編輯版本所做的。 –

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 
相關問題