我有2个表(成员,duty_sched) 我希望能够计算每个成员在duty_sched表中出现的时间。 这是我几周后搜索的内容
SELECT
members.fname,
members.lname,
(SELECT COUNT(duty_sched.id) FROM duty_sched
WHERE 'duty_sched.mbr_id' = 'members.mbr_id') AS shifts
FROM members
ORDER BY members.lname, members.fname
我得到的输出都是零,我希望它给我看的是:
姓名转移 鲍勃史密斯4 简约翰逊2
我将非常感谢能得到的任何帮助。
答案 0 :(得分:7)
删除单引号:WHERE duty_sched.mbr_id = members.mbr_id)
您还可以使用LEFT JOIN
编写查询:
SELECT
m.fname,
m.lname,
COUNT(d.id) AS shifts
FROM members AS m
LEFT JOIN duty_sched AS d
ON d.mbr_id = m.mbr_id
GROUP BY
m.mbr_id -- the Primary Key of `members`
ORDER BY
m.lname, m.fname ;
答案 1 :(得分:0)
你可以尝试类似的东西
SELECT
members.fname,
members.lname,
count(*) FROM duty_sched JOIN members
WHERE duty_sched.mbr_id = members.mbr_id
Group by duty_sched.mbr_id
ORDER BY members.lname, members.fname
答案 2 :(得分:0)
试试这个:
SELECT m.fname, m.lname, IFNULL(A.shifts, 0) shifts
FROM members m
LEFT JOIN (SELECT mbr_id, COUNT(id) shifts
FROM duty_sched GROUP BY mbr_id) A ON m.mbr_id = A.mbr_id
ORDER BY m.lname, m.fname;