如果列表中没有记录,则强制显示空值第2部分小错误

问题描述 投票:0回答:1

只想跟进我已经回答的问题 如果列表中没有记录则强制显示空值

但后来我发现了一个我无法弄清楚的小错误。如果按日期过滤掉,我想强制数据在员工列表上显示空值

我的桌子是

员工表

| emp_id | lastname | firstname |
+-------+-----------+-----------+
|  sgi01 | Doe      | John      |
|  sgi02 | Doe      | Karen     |  
|  sgi03 | Doe      | Vincent   |
|  sgi04 | Doe      | Kyle      | 
+--------+-------+--------------+

时间记录表

| emp_id | date     |time_in  |time_out  |      
+--------+----------+---------|----------|
|  sgi01 |2024-03-02|07:00:00 |16:03:22  | 
|  sgi02 |2024-03-02|07:00:00 |16:03:22  |  
|  sgi03 |2024-03-01|07:00:00 |16:03:22  |
+--------+----------+---------+----------+

结果表

| emp_id | lastname | firstname | time_in|time_out|Ctime_in   |Ctime_out  |number_of_hrs
+-------+-----------+-----------+--------+--------+-----------+-----------+-------------+
|  sgi01 | Doe      | John      |07:00:00+16:03:22|07:00:00 AM|04:03:22 PM|09:03:22
|  sgi02 | Doe      | Karen     |07:00:00+16:03:22|07:00:00 AM|04:03:22 PM|09:03:22    
|  sgi04 | Doe      | Kyle      |Null             |Null       |Null       |0
+-------+-----------+-----------------------------+--------------------------------------+

想要或者想这样显示

    | emp_id | lastname | firstname | time_in|time_out|Ctime_in   |Ctime_out  |number_of_hrs
    +-------+-----------+-----------+--------+--------+-----------+-----------+-------------+
    |  sgi01 | Doe      | John      |07:00:00|16:03:22|07:00:00 AM|04:03:22 PM|09:03:22
    |  sgi02 | Doe      | Karen     |07:00:00|16:03:22|07:00:00 AM|04:03:22 PM|09:03:22    
    |  sgi03 | Doe      | Vincent   |Null    |Null    |Null       |Null       |0
    |  sgi04 | Doe      | Kyle      |Null    |Null    |Null       |Null       |0
    +-------+-----------+-----------------------------+--------------------------------------+

MYSQL代码

SELECT e.emp_id, e.lastname, e.firstname, T.time_in, t.time_out ,

TIME_FORMAT(time_in, "%r") as Ctime_in,

TIME_FORMAT(time_out, "%r") as Ctime_out,

TIMEDIFF(time_out,time_in) as number_of_hrs

FROM `employees` as e LEFT JOIN time_records as t  on e.emp_id = t.emp_id
where t.date = '2024-03-02' OR t.date IS null \\this was answered from my previous post thanks credits to the one who answer
GROUP by e.emp_id;

由于包含日期的 where 子句为空,如果员工根本没有该日期的任何记录,我能够显示空值,但错误是如果员工有不同的记录或至少有一条记录,它永远不会显示空值..

mysql
1个回答
0
投票
SELECT e.emp_id, e.lastname, e.firstname, T.time_in, t.time_out ,
TIME_FORMAT(time_in, "%r") as Ctime_in,
TIME_FORMAT(time_out, "%r") as Ctime_out,
TIMEDIFF(time_out,time_in) as number_of_hrs
FROM `employee` as e LEFT JOIN time_records as t  
on e.emp_id = t.emp_id and t.date = '2024-03-02'

WHERE 子句和 ON 子句有区别。

当数据库通过连接两个或多个表返回记录时,会生成一个中间临时表,然后将其返回给用户。

使用left join时on和where条件的区别如下:

  1. on条件是生成临时表时使用的条件,无论on中的条件是否成立,都会从左表中返回记录。

  2. where条件是临时表生成后进行过滤的条件。此时,已经没有了left join的意义(必须返回左表中的记录),如果条件不成立,则全部过滤掉。

可以参考这个SQL JOIN:WHERE子句和ON子句有什么区别?

© www.soinside.com 2019 - 2024. All rights reserved.