假设我有一个像这样的表格消息:
id sender receiver content created_at
1 100 101 Hi 2015-12-01
2 100 101 Hello 2015-12-02
3 100 101 World 2015-11-02
4 103 101 Like 2015-11-05
5 103 101 Do 2015-11-04
6 105 102 ..................
指定了接收器后,我想获取每个用户的最新消息和消息数,即对于用户101,我想得到:
2 100 101 Hello 2015-12-02 3
4 103 101 Like 2015-11-05 2
是否可以通过单一陈述或最优雅的方式来做到这一点?
答案 0 :(得分:1)
在子查询中聚合101
的信息,然后将其连接回原始表:
select m.*, mm.maxca
from messages m join
(select m2.receiver, max(m2.created_at) as maxca, count(*) as cnt
from messages m2
where m2.receiver = 101
) mm
on m.receiver = mm.receiver and m.created_at = mm.created_at
where m.receiver = 101 ;
答案 1 :(得分:0)
这里的想法是获取最新记录,可以通过created_at排序然后使用group by来获取计数。
SELECT a.id,a.sender,a.receiver,a.content,a.created_at,count(a.sender) from (Select * from messages order by created_at desc) a group by sender ;
答案 2 :(得分:0)
SELECT x.*
, y.total
FROM my_table x
JOIN
( SELECT receiver
, sender
, MAX(created_at) max_created_at
, COUNT(*) total
FROM my_table
GROUP
BY receiver
, sender
) y
ON y.receiver = x.receiver
AND y.sender = x.sender
AND y.max_created_at = x.created_at
-- [WHERE receiver = 101]
;
+----+--------+----------+---------+------------+-------+
| id | sender | receiver | content | created_at | total |
+----+--------+----------+---------+------------+-------+
| 2 | 100 | 101 | Hello | 2015-12-02 | 3 |
| 4 | 103 | 101 | Like | 2015-11-05 | 2 |
| 6 | 105 | 102 | Re | 2015-11-04 | 1 |
+----+--------+----------+---------+------------+-------+