SQL查询一对多关系

时间:2015-09-26 16:51:17

标签: mysql sql one-to-many

这是我的数据库:

员工表:
  employee_id int(10) NOT NULL,
  firstname varchar(50) NOT NULL,
  lastname varchar(50) NOT NULL,
  username varchar(15) NOT NULL,
  password varchar(25) NOT NULL DEFAULT 'password',
  contact_number varchar(13) NOT NULL,
  email_address varchar(50) NOT NULL,
  position varchar(50) NOT NULL,
  teamleader_id int(11) DEFAULT NULL

服务表:
  service_id int(10) NOT NULL,
  ticket_id int(10) NOT NULL,
  employee_id int(10) NOT NULL,
  status varchar(15) NOT NULL,
  start_time datetime NOT NULL,
  time_in datetime DEFAULT NULL,
  time_out datetime DEFAULT NULL,
  service_notes varchar(500) DEFAULT 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 ='正在进行'

之外的所有员工。

2 个答案:

答案 0 :(得分:1)

假设您只需要一份已完成服务的员工列表(不包括那些没有且仅为每位员工显示一项服务的员工)

SELECT employee.*, COUNT(service.status)
FROM employee, service
WHERE service.employee_id = employee.employee_id
AND ( service.status IS NULL OR service.status = 'Completed' )
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;

SQL Fiddle

中测试过
CREATE TABLE employee ( employee_id INT(9) PRIMARY KEY, teamleader_id INT NOT NULL, name VARCHAR(99) NOT NULL );
CREATE TABLE service ( id INT(9) PRIMARY KEY, employee_id INT(9) NOT NULL, status VARCHAR(99) NOT NULL );
INSERT INTO employee VALUES (1, 1, 'Bob');
INSERT INTO employee VALUES (2, 1, 'Alice');
INSERT INTO service VALUES (1, 2, 'Complete');
INSERT INTO service VALUES (2, 2, 'WIP');
INSERT INTO service VALUES (3, 2, 'Ongoing');

答案 1 :(得分:1)

您只需要在查询中添加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

它过滤重复的