Reputation: 11750
I want to select the articles that have 3 or more comments. I use MySQL and I have the following tables with their respective fields:
ARTICLE: art_id (primary key), art_title, art_body, art_date, art_author, art_lang
COMMENT: com_id (primary key), com_body, com_date, com_author, com_article (foreign_key)
MySQL engine: INNO_DB
Relation: com_article - art_id
How can I perform this query?
Upvotes: 0
Views: 45
Reputation: 2483
A simple way would be using a HAVING keyword, like:
SELECT article.*, COUNT(comment.com_id) as comment_count
FROM comments
LEFT OUTER JOIN article ON article.art_id = comments.com_article
GROUP BY article.art_id
HAVING comment_count > 3
Briefly, this query will go through all the comments, group them by id of the article, count how many comments are there for every article and them will pick only those "bunches" which have 3+ count. We also join in article table, as we eventually need the articles and select only article's fields. Hope this is clear.
This might be not the most optimal solution, but should work well for relatively small tables.
Upvotes: 1