简体   繁体   中英

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. The data is basically switch states and is sent up to the server only when the switch state changes.

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.

`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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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