Mysql 一对多关系的SQL查询
这是我的数据库: 员工表:Mysql 一对多关系的SQL查询,mysql,sql,one-to-many,Mysql,Sql,One To Many,这是我的数据库: 员工表: employee\u id int(10)不为空, firstname varchar(50)不为空, lastname varchar(50)不为空, 用户名varchar(15)不为空, password varchar(25)非空默认“password”, 联系人号码varchar(13)不为空, 电子邮件地址varchar(50)不为空, 位置varchar(50)不为空, teamleader\u id int(11)默认为空 服务表: 服务\u id in
employee\u id int(10)不为空,
firstname varchar(50)不为空,
lastname varchar(50)不为空,
用户名varchar(15)不为空,
password varchar(25)非空默认“password”,
联系人号码varchar(13)不为空,
电子邮件地址varchar(50)不为空,
位置varchar(50)不为空,
teamleader\u id int(11)默认为空
服务表:
服务\u id int(10)不为空,
ticket\u id int(10)不为空,
employee\u id int(10)不为空,
状态varchar(15)不为空,
开始时间日期时间不为空,
time\u在datetime中默认为空,
time\u out datetime默认为空,
service\u notes varchar(500)默认值为NULL
查询:
SELECT * FROM employee AS e
LEFT JOIN service AS s ON e.employee_id = s.employee_id
WHERE (s.status IS NULL OR s.status = 'Completed')
AND e.teamleader_id = ?
编辑:
我想选择除service.status='Continuous'之外的所有员工,假设您只需要已完成服务的员工列表(不包括未完成服务的员工,并且每个员工只显示一项服务)
SELECT employee.*, COUNT(service.status)
FROM employee LEFT JOIN service ON service.employee_id = employee.employee_id
WHERE employee.employee_id NOT IN ( SELECT DISTINCT service.employee_id FROM service WHERE service.status = 'Ongoing')
AND teamleader_id = 1
GROUP BY employee.employee_id;
或者如果您确实想列出尚未完成任何服务的员工
SELECT employee.*, COUNT(service.status)
FROM employee LEFT JOIN service ON service.employee_id = employee.employee_id
WHERE ( service.status IS NULL OR service.status = 'Completed' )
AND teamleader_id = 1
GROUP BY employee.employee_id;
或者,如果您想要除service.status=‘持续’之外的所有
SELECT employee.*, COUNT(service.status)
FROM employee LEFT JOIN service ON service.employee_id = employee.employee_id
WHERE employee.employee_id NOT IN ( SELECT DISTINCT service.employee_id FROM service WHERE service.status = 'Ongoing')
AND teamleader_id = 1
GROUP BY employee.employee_id;
测试
您只需将DISTINCT添加到查询中:
SELECT DISTINCT e.* FROM employee e LEFT JOIN service s ON e.employee_id = s.employee_id
WHERE(s.status is null OR s.status = 'Completed') and teamleader_id = 3
它会过滤重复的员工如果我想选择除服务状态为“正在进行”的员工之外的所有员工,该怎么办
SELECT DISTINCT e.* FROM employee e LEFT JOIN service s ON e.employee_id = s.employee_id
WHERE(s.status is null OR s.status = 'Completed') and teamleader_id = 3