表Users
有5行,但是当我们在结果中使用此查询时,我们只看到一行。
对于每一行,我们希望从表Users
获取所有行并从表q.Status = 'no'
获取Quest
。请告诉我,如何做到这一点?
SELECT
*,
ifnull(count(q.Status = 'no'),0) as CountQuestionsNew
FROM
Users as u
LEFT JOIN Quest as q on q.UserID = u.UserID
WHERE
u.UserID != '453'
答案 0 :(得分:1)
你在找这样的东西吗?
SELECT u.*, COALESCE(q.CountQuestionsNew, 0) CountQuestionsNew
FROM Users u LEFT JOIN
(
SELECT UserID, SUM(status = 'no') CountQuestionsNew
FROM Quest
GROUP BY UserID
) q
ON u.UserID = q.UserID
WHERE u.UserID <> '453'
这是 SQLFiddle 演示