我在SQL命令中遇到问题。
我有一个问题表,另外还有问题的可能答案,以及其他用户回复。
想象一下以下示例:
问题1 :谁将赢得半决赛?
Aswners :A)葡萄牙B)西班牙
回复:10人投票B)西班牙,0人投票A)葡萄牙
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
我的意思是从中获取
SELECT
结果:
西班牙10
葡萄牙0
但是我不能,我不知道怎么做,因为我的方式,我总是只得到回复表上回复的asnwers的结果。像这样:
西班牙10
答案 0 :(得分:6)
您必须从问题开始,然后LEFT JOIN
回复。
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
使用您当前的查询,您甚至不需要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用于SQL Fiddle的第二个查询,返回:
ANSWER TOTAL
Spain 10
Portugal 0
答案 1 :(得分:2)
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;
使用左连接而不是内连接。
修改:加入更新。
答案 2 :(得分:0)
你的查询应该是这样的 -
SELECT a.answer, COUNT(r.id) as total
FROM questions q
INNER JOIN JOIN answers a ON q.id = a.id_question
LEFT JOIN REPLIES r ON a.id = r.id_answer
WHERE
q.id=1
GROUP BY
a.answer
这里重要的是count(r.id)
获取Portugal 0