我正在尝试将3个表连接到一个select语句中,但如果没有出现,则计算一个表的出现,同时仍显示记录。
我的例子可以在我放在一起的快速sqlFiddle中看到。我试图使用左连接,但它不会产生我想要的结果。
http://sqlfiddle.com/#!6/e2840/8
这是SQL语句:
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID
LEFT JOIN Users as U ON A.UserId = U.UserID
WHERE A.QuestionID = 1
GROUP BY O.OptionID,O.OptionName
我希望它返回的是选项表中的所有行,如果没有找到该选项的答案,则在总列中显示0。
目前的小提琴回归:
我希望它返回:
答案 0 :(得分:2)
您正在使用带有LEFT JOIN的WHERE子句,这使其像内部联接一样。
试试这个:
SELECT O.OptionID, O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID
and A.QuestionID = 1
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP BY O.OptionID,O.OptionName
答案 1 :(得分:2)
选择答案:
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN
(
SELECT OPTIONID,USERID
FROM Answers WHERE QuestionID = 1
) AS A ON O.OptionID = A.OptionID
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP BY O.OptionID,O.OptionName
答案 2 :(得分:0)
尝试下面的一些事情......
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID and A.questionId=1
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP BY O.OptionID,O.OptionName
答案 3 :(得分:0)
未引用Users表,并且这与使用sqlfiddle中的数据匹配预期结果。
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID
AND A.QuestionID = 1
GROUP BY O.OptionID,O.OptionName
顺便说一下:使用子查询没有任何好处。添加的连接条件完成相同的工作。
但是,通过避免冗余连接,您将获得优势。
答案 4 :(得分:0)
与@mjsqu相同但会避免子集。这是加入子集的更好方法
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID and A.QuestionID = 1
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP BY O.OptionID,O.OptionName