[英]Select records if the count of related records is less than a number
我有兩個表, Article
和Comments
。 現在,我想知道少於5條評論的文章數量。 我怎樣才能做到這一點?
文章:
id | author_id | title | cotent
評論:
id | article_id | author_id | content
編輯:原來的問題是關於大於,但是現在我實際上想要小於(例如,<5)。 如果沒有文章的評論記錄,則似乎未列出該文章。
嘗試這個
SELECT a.id, COUNT(*)
FROM
articles a
LEFT OUTER JOIN comments c ON a.id=c.article_id
GROUP BY a.id
HAVING COUNT(*) > 5
這將返回所有評論超過5 articles
id
,並帶有各自的評論數
加入兩個表以獲取文章的評論,然后按文章ID將其分組以了解每個文章的評論數。
試試這個:
select art.id,count(*) as comment_count
from articles art
inner join comments com on art.id=com.article_id
group by art.id
having comment_count>5
對於評論<= 5的文章:
select art.id,count(*) as comment_count
from articles art
left join comments com on art.id=com.article_id
group by art.id
having comment_count<=5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.