MySQL : Make HAVING select also "null"

rachids picture rachids · Dec 20, 2012 · Viewed 10.6k times · Source

I have two tables : dilemme and like. The first one contains articles and the second one contains votes. The script SELECT randomly one article to show and the user can vote (it's like and dislike).

I want to make a query that shows only the articles that have more than - 5 voting, the articles that has no vote are equal to 0.

So I tried this :

SELECT d.ph1, d.ph2, d.id, SUM(l.vote) AS score
FROM dilemme d
LEFT JOIN like l
ON d.id = l.id_dilemma
WHERE d.valid = 'yup'
GROUP BY d.id HAVING SUM(l.vote) > 0

It shows me correctly the rows that have at least one vote and that the sum of the votes are more than 0. Which is nice but, how to select also articles without vote ?

I tried a bunch of things and did some research but can't fix my problem. I thought about INSERT INTO like a vote of 0 but I don't think its a good idea since it won't be very an optimized solution.

Answer

Michael Fredrickson picture Michael Fredrickson · Dec 20, 2012

This should include either articles that have positive votes, or include articles with no votes by using COUNT(l.id_delemma) = 0

SELECT d.ph1, d.ph2, d.id, SUM(l.vote) AS score
FROM dilemme d
LEFT JOIN like l
ON d.id = l.id_dilemma
WHERE d.valid = 'yup'
GROUP BY d.id 
HAVING 
    SUM(l.vote) > 0
    OR COUNT(l.id_delemma) = 0