2017-05-04 16 views
0

假設我在PostgreSQL中有這兩個表。如何合併兩個不同的查詢

TABLE "Likes" (
    id, 
    post-id (foreign key pointing to "Post" table) 
) 

TABLE "Post" (
    id, 
    body, 
    date 
) 

我想要做的是獲取所有帖子和每個人擁有的喜歡數量。

我寫此查詢:

SELECT "post-id", COUNT(*) AS "likes" FROM "Likes" 
GROUP BY "post-id"; 

將返回這樣的事情:

------------------- 
| post-id | likes | 
------------------- 
| 1  | 9  | 
------------------- 
| 4  | 2  | 
------------------- 

但我仍然需要與有關獲取職位的所有信息的一個合併此查詢。 ..所以最後,我想這樣的事情:

--------------------------------------------------- 
| id | likes | body     | date  | 
--------------------------------------------------- 
| 1 | 9  | This is a post!  | 2017-05-03 | 
--------------------------------------------------- 
| 2 |  | Tasdasdas!   | 2017-05-03 | 
--------------------------------------------------- 
| 4 | 2  | This is another post! | 2017-05-04 | 
--------------------------------------------------- 
| 5 |  | ssdasdasdadadass  | 2017-05-04 | 
--------------------------------------------------- 

我的問題是,我不知道如何將「likes」列添加到提取所有帖子的查詢中,因爲只有某些帖子有喜歡。

在此先感謝!^_^

回答

2

你想要的是典型案例LEFT JOIN

SELECT post.*, COUNT(likes.id) likes 
FROM  post 
LEFT JOIN likes ON post.id = likes.post_id 
GROUP BY post.id 

這樣,您就可以SELECT post.*因爲GROUP BY post.id意味着functional dependency

旁註:您的標識符的命名非常奇怪。你應該儘量避免引用標識符,它只會讓你的查詢更難閱讀。

+0

謝謝,它的工作! :D另外,我通常不會使用引號,但出於某種原因,我被迫使用,否則它將無法工作。我使用phpPgAdmin來管理數據庫並測試查詢,如果標識符不是全部在引號內,它會出錯。 – Tirafesi

+0

@Tirafesi我並不是說你不需要報價。當你有這樣的標識符時,你真的需要它。我在說,你不應該首先使用這樣的標識符。或者,至少,沒有他們,你的工作會更簡單。但如果你能忍受它,就使用它們。 – pozs

+0

我不明白你的意思......你能告訴我一個正確的標識符是什麼樣的例子嗎? – Tirafesi

1
Select p.id, c."likes", p.body, p.date 
from Posts p 
left join 
(
SELECT "post-id", COUNT(*) AS "likes" FROM "Likes" 
GROUP BY "post-id" 
) c on p.id = c."post-id";