2015-09-26 155 views
0

這裏是我的數據庫:SQL查詢一對多的關係

Employee表:
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的那些所有員工= '正在進行'

回答

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

你只需要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 

它過濾重複

+0

如果我要選擇那些除了與service.status =「正在進行的」所有員工 – Mikael1