簡體   English   中英

SQL查詢一對多關系

[英]SQL Query for one to many relationship

這是我的數據庫:

員工表:
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 ='Ongoing'以外的所有員工

假設您只想要一份已完成一項服務的員工列表(不包括那些尚未完成且僅向每位員工顯示一項服務的員工)

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 ='Ongoing'之外的所有內容

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');

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

它過濾重復的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM