简体   繁体   English

使用if语句从多个表中进行MySQL SELECT

[英]MySQL SELECT from multiple tables with if statement

I have got two tables in a database to track who is currently onsite. 我在数据库中有两个表来跟踪当前在场的人员。 There is a list of all staff members with their staff number, and a clock in/out log. 列出所有工作人员及其工作人员编号,以及上班/下班日志。

What I am trying to do is create a daily report of who is on site and who is absent. 我想做的是创建一份关于谁在现场和谁不在的每日报告。 To do this I am checking the clock_log table for all records from today's date, like so: 为此,我正在检查clock_log表中是否有今天日期以来的所有记录,如下所示:

SELECT `Clock_Log`.Clock_Number, `Clock_Log`.Date, `Clock_Log`.Time_In,
`Clock_Log`.Time_Out, IF(`Clock_Log`.Shift_Ended = 0, 'On Site', 'Shift Ended') 
AS Status FROM `Clock_Log` WHERE Date = CURDATE();

Which outputs something like: 输出如下:

Clock_Number | Date       | Time_In  | Time_Out | Status
123          | 2019-02-14 | 07:00:00 | 00:00:00 | On Site
456          | 2019-02-14 | 07:00:00 | 15:00:00 | Shift Ended

789          | 2019-02-14 | 00:00:00 | 00:00:00 | Absent

What I now need to do is select all records from the list of all staff, who have not clocked in for today, and append those to the results with the status set to Absent. 我现在需要做的是从所有今天尚未上班的员工列表中选择所有记录,并将这些记录附加到结果设置为“缺席”的结果中。 As the third entry above. 作为上面的第三项。

Is this possible? 这可能吗? If not could an additional column be added to the end which simply lists the numbers who aren't clocked in? 如果不能,是否可以在末尾添加一列,该列仅列出未计时的数字?

Use your staff table as your FROM, then left join this query to it 将您的人员表用作FROM,然后将其加入该查询

Also, aliases 另外,别名

select t1.*, t2.*
from all_staff t1
left join 
    (
    SELECT t3.Clock_Number, 
           t3.Date, 
           t3.Time_In,
           t3.Time_Out, 
           IF(t3.Shift_Ended = 0, 'On Site', 'Shift Ended') AS Status 
    FROM `Clock_Log` t3 WHERE Date = CURDATE() 
    ) t2
on t1.clock_number = t2.clock_number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM