如何从第一个表中获取所有行与第二个表中的count行?

时间:2014-12-23 21:57:03

标签: mysql sql

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'

1 个答案:

答案 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 演示