gpt4 book ai didi

mysql - 如何按日期从2个表中选择数据

转载 作者:行者123 更新时间:2023-11-29 19:06:17 25 4
gpt4 key购买 nike

我有两个表:

在此表中我有所有员工:

Employe (id_employe, name, tel)

在此表中,我列出了在场的所有员工:

Present (id_present, date, #id_empoye)

现在,我想选择所有缺勤的员工(不在表中的所有员工)以及缺勤日期。

很抱歉我的英语不好,我需要帮助!

这是我的 sql 查询:

select id_employe, date from employe, absence where id_employe not in
(select id_personnel from absence group by date) group by id_employe
order by date asc;

最佳答案

您首先要做的是使用子查询来获取所有员工的工作日记录。我假设如果那天有人去上类,那就是工作日。因此,我选择每个不同的工作日期并将其添加到每个员工身上。我说 ON 1=1 是因为该条件始终为真,并且将为我提供每位员工和工作日的记录。

然后,我使用该临时表并加入 Present 表。如果员工在工作日出勤,他将从 Present 表中连接一条记录,因此我只能查找没有连接的记录,即 p.id_present IS NULL

WITH WorkDateTable AS (
SELECT e.id_employe, p.work_date
FROM Employe e LEFT JOIN (SELECT DISTINCT work_date FROM Present) p ON 1=1)
SELECT wd.id_employe, wd.work_date AS AbsenceDate
FROM WorkDateTable wd
LEFT JOIN Present p ON p.work_date = wd.work_date AND p.id_employe = wd.id_employe
WHERE p.id_present IS NULL
ORDER BY AbsenceDate, wd.id_employe

请注意,date 是保留字,您不能将其用于字段,这就是我将其更改为 work_date 的原因。您的最终结果是工作日期列表以及当天缺勤人员的 ID。

如果您想知道谁在特定日期或日期范围内缺勤,只需在 WHERE 语句末尾添加一个子句即可。

编辑:MySQL 不支持使用WITH 子句。因此,将WITH中的语句移动到FROM语句中,如下所示:

SELECT wd.id_employe, wd.work_date AS AbsenceDate
FROM (SELECT e.id_employe, p.work_date
FROM Employe e LEFT JOIN (SELECT DISTINCT work_date FROM Present) p ON 1=1) wd
LEFT JOIN Present p ON p.work_date = wd.work_date AND p.id_employe = wd.id_employe
WHERE p.id_present IS NULL
ORDER BY AbsenceDate, wd.id_employe

此查询应该适用于 MySQL 或 Oracle 搜索。

关于mysql - 如何按日期从2个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43477189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com