mysql - MySQL显示范围之间的所有日期虽然没有记录
问题描述
我有表 xDateList 包含:
+---------+
xDateList
+---------+
2018-11-01
2018-11-02
2018-11-03
2018-11-04
2018-11-05
还有表扫描日志
--------------------------------------
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
感谢你们对我的帮助
解决方案
您需要更改LEFT JOIN
. 永远记住,为了考虑特定表中的所有行;该特定表应该是联接中最左侧的表。
ON
此外,无论何时进行 LEFT JOIN,都应在子句中指定右侧表的条件;否则 WHERE 子句中的条件可以有效地将其转换为 INNER JOIN。
此外,在这种情况下,GROUP BY
应该在 上xDateList.date
显示与值对应的所有行xDateList.date
。而且,我们需要确保列表中的所有非聚合列也在子句SELECT
中指定。GROUP BY
请检查:在 MySql 中执行查询时与 only_full_group_by 相关的错误
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 | | | |
推荐阅读
- javascript - 我更改了 xaxis 的最小值和最大值,但是如何更改“导航器”?
- r - 在 dplyr 中对选定列求和(使用 select() 方法)
- sql - 查询执行慢:执行需要很长时间 => 很奇怪为什么?
- reactjs - React Hooks UseRef 问题
- r - bbmle 的 NaN 错误
- regex - JMeter:如何为此请求 URL 编写正则表达式提取器
- git - 让 Travis 构建一个分支,将分支作为子模块推送到该分支并运行脚本
- php - 快速连续 XmlHttpRequest 不起作用
- java - 无法构造“类名”的实例(尽管至少在 Creator 上存在)
- go - 如何解决类型系统的浅接口匹配?(协变结果类型)