我有两张桌子:
reviewStatusPhases - id|name
和
userPhase - id|reviewStatusPhase_id|user_id|created_at|updated_at
reviewStatusPhases 表已插入记录(有效,无效,暂停,已终止...), userPhase 为空。
表格通过
连接 userPhase.reviewStatusPhase_id = reviewStatusPhases.id
一对一。
是否有可能在一个查询中获得所有reviewStatusPhases,并确定每个阶段有多少用户?在这种情况下,我会得到这样的东西:
Active (0 Users)
Inactive (0 Users)
On Pause (0 Users)
Terminated (0 Users)
答案 0 :(得分:2)
我在这里做了一些假设(例如INNER JOIN与连接中的LEFT JOIN以及计数中的DISTINCT),但听起来你只是想要
SELECT reviewStatusPhases.name, COUNT(DISTINCT userPhase.user_id)
FROM userPhase INNER JOIN reviewStatusPhases
ON userPhase.reviewStatusPhase_id = reviewStatusPhases.id
GROUP BY reviewStatusPhases.name
答案 1 :(得分:2)
查询如下:
SELECT r.name as `name`, count(u.id) as `count` FROM reviewStatusPhases r LEFT OUTER JOIN userPhase u ON r.id = u.reviewStatusPhase_id GROUP BY r.name
答案 2 :(得分:1)
使用LEFT JOIN
,如下所示:
SELECT COUNT(m.UserId) FROM Table1 m
LEFT JOIN Table2 k ON k.StatusId = m.StatusId
WHERE k.Status = 'Inactive'
您可以轻松使用状态列来跟踪用户及其活动。在您的情况下, ReviewStatus 。
答案 3 :(得分:1)
我希望以下内容有所帮助
SELECT RPS.Name, COUNT(UP.user_id)
FROM reviewStatusPhases RPS
LEFT OUTER JOIN userphases UP ON RPS.id = UP.reviewStatusPhase_id
GROUP BY RPS.Name
ORDER BY RPS.Name
答案 4 :(得分:0)
SELECT
DISTINCT s.s_level AS 'Level',
COUNT(DISTINCT s.s_id) AS Schools,
COUNT(DISTINCT st.st_id) AS Teachers
FROM schools AS s
JOIN school_teachers AS st ON st.st_school_idFk = s.s_id AND st.st_status = 1
WHERE s.s_status = 1
GROUP BY s.s_level