根据机器ID列(' mid'),我有两个MYSQL表,我这是一个LEFT JOIN。
机'表
+-----+-------------+-------------+-----+---------------------+
| mid | machineName | ipAddress | nid | modified |
+-----+-------------+-------------+-----+---------------------+
| 1 | machine1 | 192.168.1.1 | 16 | 2018-01-28 19:48:53 |
| 2 | machine2 | 192.168.2.1 | 16 | 2018-01-29 16:28:11 |
+-----+-------------+-------------+-----+---------------------+
' user_reverts'表
+----+-----+-----+---------------------+
| id | uid | mid | modified |
+----+-----+-----+---------------------+
| 11 | 189 | 1 | 2018-01-30 10:01:10 |
| 13 | 189 | 2 | 2018-01-30 12:11:50 |
| 14 | 190 | 1 | 2018-01-26 17:09:17 |
| 15 | 190 | 2 | 2018-01-25 15:51:31 |
| 16 | 189 | 2 | 2018-01-30 19:48:58 |
+----+-----+-----+---------------------+
查询计算自每天开始以来用户在每台计算机上进行的还原次数,并按机器对其进行分组。
SELECT machines.mid as mid, machines.machineName as machineName,
machines.ipAddress as ipAddress, coalesce(reverts.count, 0) as count,
coalesce(reverts.modified,'never') as reverted FROM
(SELECT mid, machineName, INET6_NTOA(ipAddress) as ipAddress FROM machines) machines
LEFT JOIN
(SELECT machines.mid,user_reverts.modified,count(*) as count FROM machines
INNER JOIN user_reverts ON user_reverts.mid=machines.mid AND user_reverts.uid = 189
WHERE DATE(user_reverts.modified) = CURDATE() group by user_reverts.mid) reverts
ON reverts.mid = machines.mid
它运作良好,但我希望“恢复”'列显示最新的时间和日期,因此预期的结果将是
+-----+-------------+-------------+-------+---------------------+
| mid | machineName | ipAddress | count | reverted |
+-----+-------------+-------------+-------+---------------------+
| 1 | machine1 | 192.168.1.1 | 1 | 2018-01-24 10:01:10 |
| 2 | machine2 | 192.168.2.1 | 2 | 2018-01-30 19:48:58 | (latest)
+-----+-------------+-------------+-------+---------------------+
我试图替换
coalesce(reverts.count, 0)
与
MAX(reverts.count, 0)
但我收到一条错误消息。 我该怎么做? 感谢
答案 0 :(得分:1)
您可以添加其他列并简化查询:
SELECT machines.mid as mid
, machines.machineName as machineName
, INET6_NTOA(ipAddress) as ipAddress
, coalesce(count(*), 0) as count
, coalesce(MAX(user_reverts.modified),'never') as reverted -- latest revert
FROM machines
LEFT JOIN user_reverts
ON ( user_reverts.mid=machines.mid AND user_reverts.uid = 189 )
WHERE DATE(user_reverts.modified) = CURDATE()
GROUP BY machines.mid
;
查看this SQLFiddle(当然,确切的表格定义可能与您的不同)。