简体   繁体   English

SQL 连接查询计算当天数据返回 NULL 当没有当天数据时

[英]SQL join query calculate data for current day return NULL when there is no data for current day

I have 4 sensors sending data to the server on events.我有 4 个传感器向服务器发送事件数据。 The data is basically switch states and is sent up to the server only when the switch state changes.数据基本上是开关状态,只有在开关 state 发生变化时才会发送到服务器。

I am trying to show the data for just a specific day (midnight to midnight).我试图显示特定日期(午夜到午夜)的数据。 The query works, but when is no data for the sensor for the date range selected the sensor does not show up in my list.查询有效,但是当所选日期范围内的传感器没有数据时,传感器不会显示在我的列表中。 I want to still have the sensor in the list even though there is no data.即使没有数据,我也想在列表中保留传感器。 I use the result of the query to populate the table on my web page and want to show all sensors, even the ones that are offline or ahs just not communicated.我使用查询结果来填充我的 web 页面上的表,并希望显示所有传感器,即使是那些离线或只是未通信的传感器。

`SELECT columns_from_t1, columns_from_t2, SUM(column_t2) AS total
FROM table1 AS ti
LEFT JOIN table2 AS t
ON ti.id=t.id
WHERE CAST(datetimecolumn AS DATE) = CURDATE() OR datetimecolumn IS NULL
GROUP BY ti.columnname
ORDER BY t.datetimecolumn ASC`

Try moving the WHERE criteria to the ON clause of the left join:尝试将WHERE条件移动到左连接的ON子句:

SELECT columns_from_t1, columns_from_t2, SUM(column_t2) AS total
FROM table1 AS ti
LEFT JOIN table2 AS t
    ON ti.id = t.id AND
       (CAST(t.datetimecolumn AS DATE) = CURDATE() OR t.datetimecolumn IS NULL)
GROUP BY ti.columnname
ORDER BY t.datetimecolumn;

The problem with restricting datetimecolumn in the WHERE clause is that it can cause non matching records to prematurely be filtered off.WHERE子句中限制datetimecolumn的问题是它可能导致不匹配的记录过早地被过滤掉。

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

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