我需要在多个表上运行此查询:
设备、设备_警报、设备_文件、设备_FP、设备_用户
SELECT deviceID, COUNT(acepted) AS TT
FROM devices
WHERE acepted = 0
GROUP BY deviceID;
并获取每个接受=0的设备ID的总行数
这是获得结果的最佳方式。使用 union all 或者有不同的方式
SELECT deviceID, COUNT(*) AS TT
FROM (
SELECT deviceID, acepted
FROM devices
WHERE acepted = 0
UNION ALL
SELECT deviceID, acepted
FROM device_alarms
WHERE acepted = 0
UNION ALL
SELECT deviceID, acepted
FROM device_files
WHERE acepted = 0
UNION ALL
SELECT deviceID, acepted
FROM device_FP
WHERE acepted = 0
UNION ALL
SELECT deviceID, acepted
FROM device_users
WHERE acepted = 0
) AS all_tables
GROUP BY deviceID;
或者这个在性能方面更好
SELECT
deviceID,
SUM(TT) AS total_count
FROM (
SELECT deviceID, COUNT(acepted) AS TT
FROM devices
WHERE acepted = 0
GROUP BY deviceID
UNION ALL
SELECT deviceID, COUNT(acepted) AS TT
FROM device_alarms
WHERE acepted = 0
GROUP BY deviceID
UNION ALL
SELECT deviceID, COUNT(acepted) AS TT
FROM device_files
WHERE acepted = 0
GROUP BY deviceID
UNION ALL
SELECT deviceID, COUNT(acepted) AS TT
FROM device_FP
WHERE acepted = 0
GROUP BY deviceID
UNION ALL
SELECT deviceID, COUNT(acepted) AS TT
FROM device_users
WHERE acepted = 0
GROUP BY deviceID
) AS counts
GROUP BY deviceID;
如果您的表存储相似的数据,为什么不将它们保存在一个表中并按类型列分开?我认为这会是更好的解决方案