MySQL显示范围之间的所有日期完全没有记录

时间:2018-11-28 02:56:33

标签: mysql date

我有xdateList表包含:

+---------+
 xDateList 
+---------+
2018-11-01
2018-11-02
2018-11-03
2018-11-04
2018-11-05

还有表ScanLog

--------------------------------------
ID  Name   ScanDate               Code
--------------------------------------
1   John   2018-11-02 07:00:00    IN
1   John   2018-11-02 10:00:00    OUT
1   John   2018-11-04 08:00:00    IN
1   John   2018-11-04 12:00:00    OUT

我已经尝试过了,但是它不能显示xDateList上的所有记录,它只显示表ScanLog上的记录

select xDateList.date, 
       scanlog.name, 
       MIN(scanlog.scandate) AS `IN`, 
       MAX(scanlog.scandate) AS `OUT`
from scanlog 
left JOIN xDateList ON xDateList.date = date(scanlog.scandate) 
where scanlog.id='1' 
GROUP BY DATE(scanlog.scandate)

我想要这样的结果

--------------------------------------------
Date         ID   Name   In         Out
--------------------------------------------
2018-11-01   1    John   
2018-11-02   1    John   07:00:00   10:00:00
2018-11-03   1    John
2018-11-04   1    John   08:00:00   12:00:00
2018-11-05   1    John

谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要更改LEFT JOIN中表的顺序。始终记住这一点,以便考虑特定表中的所有行;那个特定的表应该是Join中最左边的表。

此外,每当进行LEFT JOIN时,应在ON子句中指定右侧表的条件;否则,WHERE子句中的条件可以将其有效地改为INNER JOIN。

此外,在这种情况下,GROUP BY应该在xDateList.date上以显示与xDateList.date值相对应的所有行。并且,我们需要确保SELECT子句中也指定GROUP BY列表中所有未聚合的列。请检查:Error related to only_full_group_by when executing a query in MySql

SELECT xDateList.date, 
       scanlog.name, 
       MIN(scanlog.scandate) AS `IN`,
       MAX(scanlog.scandate) AS `OUT`
FROM xDateList  
LEFT JOIN scanlog  
  ON xDateList.date = date(scanlog.scandate) AND
     scanlog.id='1' 
GROUP BY xDateList.date, scanlog.name 

结果

| date       | name | IN                  | OUT                 |
| ---------- | ---- | ------------------- | ------------------- |
| 2018-11-01 |      |                     |                     |
| 2018-11-02 | John | 2018-11-02 07:00:00 | 2018-11-02 10:00:00 |
| 2018-11-03 |      |                     |                     |
| 2018-11-04 | John | 2018-11-04 08:00:00 | 2018-11-04 12:00:00 |
| 2018-11-05 |      |                     |                     |

View on DB Fiddle