Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL command to show 0 if doesn't exist in the join table

Tags:

sql

mysql

I'm having a problem in a SQL command.

I have a table with questions, other with the possible answers to that questions and other with the replies from the users.

Imagine the following example:

Question 1: Who will win semi-final?
Aswners: A) Portugal B) Spain
Replies: 10 people voted B) Spain, 0 people voted A) Portugal

SELECT a.answer, COUNT(r.id) as total
FROM replies r
LEFT JOIN answers a ON a.id = r.id_answer
LEFT JOIN questions q ON q.id = a.id_question
WHERE q.id = 1
GROUP BY r.id_answer

My point is to get from the
SELECT the result:
Spain 10
Portugal 0

But i can't, i don't know how to do it, because the way i did, i always get only the result from the asnwers with replies on the replies table. Like this:
Spain 10

like image 689
costa Avatar asked Nov 23 '25 13:11

costa


2 Answers

You would have to start with your questions, and LEFT JOIN the replies.

SELECT a.answer, COUNT(r.id_answer) AS total
FROM questions q
JOIN answers a ON ( a.id_question = q.id )
LEFT JOIN replies r ON ( r.id_answer = a.id )
WHERE q.id = 1
GROUP BY a.id, a.answer

With your current query you don't even need the question:

SELECT a.answer, COUNT(r.id_answer) AS total
FROM answers a
LEFT JOIN replies r ON ( r.id_answer = a.id )
WHERE a.id_question = 1
GROUP BY a.id, a.answer

See this example for your second query on SQL Fiddle, that returns:

ANSWER      TOTAL
Spain       10
Portugal    0
like image 88
Peter Lang Avatar answered Nov 25 '25 02:11

Peter Lang


SELECT a.answer, COUNT(r.id) as total
FROM questions q
INNER JOIN answers a ON a.id_question  = q.id
LEFT JOIN replies r ON r.id_answer = a.id
WHERE q.id = 1
GROUP BY a.id;

Use Left join instead of inner join.

Edit : Join updated.

like image 36
manurajhada Avatar answered Nov 25 '25 04:11

manurajhada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!