7

我有 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

我能得到的任何帮助将不胜感激。

4

3 回答 3

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 ;
于 2013-01-06T01:44:46.013 回答
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
于 2013-01-06T01:46:55.807 回答
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;
于 2013-01-06T05:51:43.380 回答