我有一个 Feed 应用程序,我试图对连续的结果进行分组。 我的表看起来像这样:
postid | posttype | target | action | date | title | content
1 | userid | NULL | upgrade | 0000-01-00 00:00:00 | Upgraded 1 | exmple
1 | userid | NULL | upgrade | 0000-01-00 00:00:01 | Upgraded 2 | exmple
1 | userid | NULL | downgrade | 0000-01-00 00:00:02 | Downgraded | exmple
1 | userid | NULL | upgrade | 0000-01-00 00:00:03 | Upgraded | exmple
我希望的结果是:
postid | posttype | target | action | date | title | content
1 | userid | NULL | upgrade | 0000-01-00 00:00:01 | Upgrade 1 | exmple,exmple
1 | userid | NULL | downgrade | 0000-01-00 00:00:02 | Downgraded | exmple
1 | userid | NULL | upgrade | 0000-01-00 00:00:03 | Upgraded | exmple
正如您所见,因为升级 1 和升级 2 是连续发送的,所以它将它们组合在一起。 “Action”表是一个引用,应该用于连续分组以及postid和posttype。
我环顾四周,但没有看到任何与我的相似的东西。在此先感谢您的帮助。
最佳答案
这是另一个适用于 MySQL 变量且不需要 3 级嵌套深度的版本。第一个按 postID 和 Date 顺序对记录进行预排序,并在任何时候 Post ID、Type 和/或 action 中的一个值发生变化时为它们分配每组一个序列号。从那以后,它是一个简单的组...没有比较记录版本 T 到 T2 到 T3...如果您想要 4 或 5 个标准怎么办...您是否需要嵌套更多条目?或者只添加 2 个@ sql变量对比测试...
你的调用哪个更有效率...
select
PreQuery.postID,
PreQuery.PostType,
PreQuery.Target,
PreQuery.Action,
PreQuery.Title,
min( PreQuery.Date ) as FirstActionDate,
max( PreQuery.Date ) as LastActionDate,
count(*) as ActionEntries,
group_concat( PreQuery.content ) as Content
from
( select
t.*,
@lastSeq := if( t.action = @lastAction
AND t.postID = @lastPostID
AND t.postType = @lastPostType, @lastSeq, @lastSeq +1 ) as ActionSeq,
@lastAction := t.action,
@lastPostID := t.postID,
@lastPostType := t.PostType
from
t,
( select @lastAction := ' ',
@lastPostID := 0,
@lastPostType := ' ',
@lastSeq := 0 ) sqlVars
order by
t.postid,
t.date ) PreQuery
group by
PreQuery.postID,
PreQuery.ActionSeq,
PreQuery.PostType,
PreQuery.Action
对于标题,您可能需要调整线条...
group_concat(distinct PreQuery.Title) 作为标题,
至少这将使 DISTINCT 标题连接起来……如果不将整个查询再嵌套一个级别,则很难让最大查询日期和其他元素根据所有条件获得与该最大日期相关联的标题。
关于MySQL 按连续行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317206/