PieCloudDB中查询所有设备当前状态的SQL问题求助
解决PieCloudDB设备状态查询问题
原SQL使用INNER JOIN,导致没有操作记录的设备被过滤,要显示所有设备并将无操作记录的设备状态设为初始值OFF,可以通过以下修改实现:
修改后的SQL语句
SELECT d.device_id, d.device_name, COALESCE(o.operation, 'OFF') AS current_status FROM Devices d LEFT JOIN ( SELECT device_id, MAX(operation_id) AS max_operation_id FROM Operations GROUP BY device_id ) latest_op ON d.device_id = latest_op.device_id LEFT JOIN Operations o ON latest_op.max_operation_id = o.operation_id ORDER BY device_id;
关键修改点
- 将原查询中的两次
INNER JOIN替换为LEFT JOIN:确保Devices表中的所有设备都能被保留,即使没有对应的操作记录。 - 使用
COALESCE(o.operation, 'OFF'):当设备没有操作记录时,o.operation会返回NULL,通过COALESCE函数将其替换为初始状态OFF。
正确查询结果
| device_id | device_name | current_status |
|---|---|---|
| 1 | A | OFF |
| 2 | B | ON |
| 3 | C | OFF |
| 4 | D | OFF |
| 5 | E | ON |
内容的提问来源于stack exchange,提问作者lucky
相关产品推荐
相关产品推荐

