An article has 1 or many comments. How would I get only the articles with 0 comments?
This would be easier with a counter cache. However, I need to do this without using a counter cache.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use like this:
This could easily be adapted to return articles with a specific number or range of comments, e.g.:
In the latter case,
ncan be a specific number, like 100, or a range like1..10which ActiveRecord will turn into aBETWEENquery returning articles with 1 through 10 comments.Note that in the 0-comment case, the count is
NULL, so you can’t use the range query for that.I’ve tested this in Postgres. I don’t know if it’ll work in MySQL. I’m not sure how/if MySQL handles sub-selects for joins.
Edit: The solution pointed out by a previous commenter is easier, if you only need to know articles without comments. For count ranges, the above will work.