带连接的PostgreSQL反向查询
根据下面的模式,我试图让第一部门的所有员工都知道他们在某个特定日期缺席(如果有)的理由,如下所示带连接的PostgreSQL反向查询,sql,database,postgresql,Sql,Database,Postgresql,根据下面的模式,我试图让第一部门的所有员工都知道他们在某个特定日期缺席(如果有)的理由,如下所示 ------------------------------------------------------------------- id | department | full_name | excuse | date -------+------------+-------------------+--------------+-----------
-------------------------------------------------------------------
id | department | full_name | excuse | date
-------+------------+-------------------+--------------+-----------
10 | Sales | John Doe | NULL | 2019-01-20
20 | Sales | James Brown | NULL | 2019-01-20
30 | Sales | Adam Sanders | Fatigued | 2019-01-20
70 | Sales | Amber Philips | NULL | 2019-01-20
我已经尝试了下面的查询,但是我没有得到正确的答案
SELECT DISTINCT(emp.id) as employee_id,
emp.full_name, ab.excuse
dept.name AS department
FROM employees emp
INNER JOIN departmens dept ON emp.department_id = dept.id
LEFT JOIN absence ab ON ab.employee_id = emp.id
WHERE emp.department_id IN (1)
AND emp.id NOT IN (
SELECT att.employee_id FROM attendance att
INNER JOIN employees emp ON att.employee_id = emp.id
WHERE emp.department_id IN (1)
AND att.date BETWEEN SYMMETRIC '2019-01-20' AND '2019-01-20'
)
员工
-----------------------------------------
id | department | full_name
-------+------------+--------------------
10 | 1 | John Doe
20 | 1 | James Brown
30 | 1 | Adam Sanders
40 | 3 | Craig Wallace
50 | 3 | Lina Goode
60 | 6 | Jenny Rosewood
70 | 1 | Amber Philips
出席人数
----------------------------------------
id | employee_id | attendance_date
-------+-------------+------------------
1 | 10 | 2019-01-20
2 | 20 | 2019-01-20
-------------------------------------------------------
id | employee_id | excuse | date
-------+-------------+--------------------+------------
1 | 30 | Fatigued | 2019-01-20
2 | 20 | Feeling Sick | 2019-01-18
3 | 10 | Out Of town | 2019-01-15
缺席
----------------------------------------
id | employee_id | attendance_date
-------+-------------+------------------
1 | 10 | 2019-01-20
2 | 20 | 2019-01-20
-------------------------------------------------------
id | employee_id | excuse | date
-------+-------------+--------------------+------------
1 | 30 | Fatigued | 2019-01-20
2 | 20 | Feeling Sick | 2019-01-18
3 | 10 | Out Of town | 2019-01-15
根据所需的
结果
,您不需要子查询
。您的左连接就足够了
select distinct(emp.id) as employee_id
, dept.name
, emp.full_name
, ab.excuse
, ab.date
from employees emp
inner join departmens dept on emp.department_id = dept.id
left join absence ab on ab.employee_id = emp.id and ab.date = '2019-01-20'
where emp.department_id in (1)
根据所需的结果
,您不需要子查询
。您的左连接就足够了
select distinct(emp.id) as employee_id
, dept.name
, emp.full_name
, ab.excuse
, ab.date
from employees emp
inner join departmens dept on emp.department_id = dept.id
left join absence ab on ab.employee_id = emp.id and ab.date = '2019-01-20'
where emp.department_id in (1)