如果其他表上不存在,搜索连接查询不会显示另一行

时间:2014-02-19 02:33:39

标签: mysql

我有一个桌子尝试和员工。

尝试表

|ID | name | results   
| 1 | Paul | Passed        
| 2 | Paul | Passed   
| 3 | Paul | Failed   

员工

|ID | name | employee id
| 1 | Paul |   123
| 2 | John |   456   

预期结果

name | passed |  Failed  | 
Paul |   2    |    1     |   
John |   0    |    0     |

这是我的查询;

Select employee.name, SUM( attempts.results =  "Passed" ) AS passed,
SUM( attempts.results = "Failed" ) AS failed from employee left join attempts on employee.name = attempts.name where employee.employee_id = 123 or employee.employee_id = 456

但我的结果只有一行才是保罗。因为在桌子上尝试。约翰不在那里。

1 个答案:

答案 0 :(得分:1)

一些事情。

  • 将员工ID存储在尝试表中并加入,而不是名称。它更快,更独特。 (如果有两名员工叫保罗怎么办?)
  • 您的员工表有一个id列和一个员工ID列。不太清楚。考虑将employee id重命名为employee code
  • 您的尝试表正在存储'Passed'和'Failed',大概是varchar列。考虑重命名要传递的列并使用布尔值。是否有两个以上的结果值?你能'半程'吗?你能'突然失败'吗?

我会写这样的查询:

select e.name,
  count(case when a.results = 'Passed' then 1 else 0) as passed,
  count(case when a.results = 'Failed' then 1 else 0) as failed
from employee e
left outer join attempts a on e.name = a.name
group by e.name

或者如果你接受我的建议:

select e.id, e.name,
  count(case when a.passed = 1 then 1 else 0) as passed,
  count(case when a.passed = 0 then 1 else 0) as failed
from employee e
left outer join attempts a on e.id = a.employee_id
-- where e.id in (...)
group by e.id, e.name