我想使用查询从多个表中获取多个实体的总和。 具体来说,我想要用户的设备和消息计数。此外,该用户最后收到的消息的时间戳。 我有 3 张 table :
用户
id name (other fields)
1 Mike ...
2 John ...
3 Yay ...
4 Jim ...
设备
id user_id (other fields)
1 1 ...
2 1 ...
3 1 ...
4 2 ...
消息
id device_id message time (other fields)
1 1 Hi 2019-04-07 12:06:44 ...
2 1 Hey 2019-04-06 12:06:44 ...
3 2 Sup 2019-04-05 12:06:44 ...
4 3 Ok 2019-04-04 12:06:44 ...
5 4 Yay 2019-04-08 12:06:44 ...
...例如,对于用户 Mike
我希望最终得到:
结果
nDevices nMessages time
3 4 2019-04-07 12:06:44
有什么想法吗? 提前致谢。
最佳答案
连接 3 个表并计算列的不同值:
select
count(distinct d.id) devicescounter,
count(distinct m.id) messagescounter,
max(m.time) lastmessagetime
from users u
left join devices d on u.id = d.user_id
left join nessages m on m.device_id = d.id
where u.name = 'Mike'
如果您想要所有用户的结果:
select
u.id, u.name,
count(distinct d.id) devicescounter,
count(distinct m.id) messagescounter,
max(m.time) lastmessagetime
from users u
left join devices d on u.id = d.user_id
left join nessages m on m.device_id = d.id
group by u.id, u.name
关于MySQL 查询数据库中特定用户的连接+计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55654618/