这是我的数据表结构
id actor_id created_at updated_at 729 80 2012-09-10 17:05:59 2012-09-10 17:05:59 731 80 2012-09-10 17:04:02 2012-09-10 17:04:02 725 139 2012-09-06 13:59:08 2012-09-06 13:59:08 724 76 2012-09-06 11:31:30 2012-09-06 11:31:30 723 29 2012-09-06 09:40:22 2012-09-06 09:40:22 719 29 2012-09-06 09:24:02 2012-09-06 09:24:02 811 80 2012-09-02 17:05:59 2012-09-10 17:05:59 812 80 2012-09-01 17:04:02 2012-09-10 17:04:02
这是
的结果SELECT `te`.`id`, te.actor_id, te.created_at, te.created_at
FROM `timeline_events` AS te
ORDER BY
te.created_at DESC
LIMIT 10
我需要通过actor_id和created_at
对其进行分组以下是我最终需要的内容
id actor_id created_at updated_at count 729 80 2012-09-10 17:05:59 2012-09-10 17:05:59 2 725 139 2012-09-06 13:59:08 2012-09-06 13:59:08 1 724 76 2012-09-06 11:31:30 2012-09-06 11:31:30 1 723 29 2012-09-06 09:40:22 2012-09-06 09:40:22 2 812 80 2012-09-10 17:04:02 2012-09-10 17:04:02 2
有人可以指导我怎么做吗?
非常感谢提前
UPD 为了简化,我将再举一个例子
所以说我有下一行
1 1 (count: 2) 1 3 3 (count: 1) 4 4 => after magic function it should be 4 (count: 2) 1 1 1 (count: 3) 1 6 6 (count: 2) 6 4 4 (count 3) 4 4
所以应该按小组分开。
UPD 2 我需要这个查询来渲染时间轴。现在它显示了用户所做的所有信息,但我需要将其分组。
在
在
答案 0 :(得分:2)
我认为这可能就是你要做的事情:
select t1.id,
t1.actor_id,
max(created_at) created_at,
updated_at,
t2.total
from yourtable t1
left join
(
select count(*) total, date(created_at) dt, actor_id
from yourtable
group by actor_id, date(created_at)
) t2
on t1.actor_id = t2.actor_id
and date(t1.created_at) = t2.dt
group by t1.actor_id, date(t1.created_at)
order by t1.created_at desc
我按actor_id
分组,使用DATE()
功能
答案 1 :(得分:1)
我自己找到解决方案
这是查询
SET @i = 0; SELECT COUNT(`wrapper`.`id`) AS 'count', GROUP_CONCAT(`wrapper`.`type` SEPARATOR ',') as 'types' FROM ( SELECT @prev := ( SELECT prev_te.actor_id FROM `timeline_events` AS prev_te WHERE prev_te.created_at > te.created_at ORDER BY prev_te.created_at ASC LIMIT 1 ) AS 'prev_actor_id', IF( @prev = te.`actor_id` OR @prev IS NULL, @i, @i := @i + 1 ) AS 'actor_id_group', `te`.* FROM `timeline_events` AS te ORDER BY te.created_at DESC, te.id DESC ) AS `wrapper` GROUP BY `wrapper`.`actor_id_group` LIMIT 10
这里是the proof link; - )
This website真的帮助了我
我正在使用包装器进行分组,因为mysql没有按变量分组,如果有人知道更好的解决方案,请告诉我
答案 2 :(得分:0)
在GROUP BY actor_id
子句之前添加order by
。
最新编辑:
select distinct actor_id, count(actor_id), created_at from actors group by actor_id
order by created_at desc;
答案 3 :(得分:0)
SELECT
te
。id
,te.actor_id,te.created_at,te.updated_at, COUNT(*)FROMtimeline_events
AS te GROUP BY te.actor_id, te.created_at ORDER BY te.created_at DESC 限制10