按日期MYSQL在活动流中按订单分组

时间:2013-10-29 18:09:01

标签: php mysql android-activity group-by sql-order-by

我从这里尝试了很多解决方案,但没有一个解决了我的问题!我有以下表结构:

|Column|Type|
|------
|activity_id| int(10) PRIMARY
|user_id| int(10)
|type| varchar(255)
|activity| varchar(255)
|item_id| int(11)
|secundary_id| int(11)
|date| datetime

我正在构建一个活动流,在此表中我将记录为

“John(user_id)评论(活动)帖子(type => item_id)5小时前(日期)”

我打算做以下结构:

“John,Marie和+2在5小时前发表评论”

到目前为止,我能够进行此连接,但我无法按日期成功订购记录。我在自己的表中尝试了一些内连接,但是由于我无法检索未按(type,activity,item_id)分组的其他活动类型,例如:

“John(user_id)发布(活动)帖子(type => item_id)5小时前(日期)”

当我使用JOINS时,我只能按记录分组。这是我的实际查询:

SELECT t.*, GROUP_CONCAT(DISTINCT user_id ) AS users FROM (
SELECT *
FROM activity
   ORDER BY date DESC 
)t
GROUP BY type, activity, item_id
ORDER BY date DESC

我已经尝试过这里列出的一些解决方案:Select the 3 most recent records where the values of one column are distinct 但是当我加入桌子时,我丢失了非分组记录! 有没有人有另一种想法?谢谢你!

/ **编辑 - 结果

activity_id     user_id     type    activity    item_id     secundary_id    date    users
865         32  update  comment     20  22  2013-10-29 15:03:49     32,34
858         36  update  post    20  NULL    2013-10-29 13:50:59     36
864         32  post    comment     2615    21  2013-10-29 14:55:58     32,34,36
856         36  post    comment     2616    14  2013-10-29 13:50:10     36,39,34,32
872         32  post    comment     2617    28  2013-10-29 15:46:20     32
852         34  post    post    2615    NULL    2013-10-29 13:47:25     34
854         32  post    post    2616    NULL    2013-10-29 13:49:13     32
870         32  post    post    2617    NULL    2013-10-29 15:36:57     32

这就是我上面的查询所得到的,但是例如有4个用户评论的item_id 2616,没有按最后一个用户评论日期排序,例如我有以下记录:

activity_id user_id type activity item_id secundary_item date
856     36  post    comentar    2616    14  2013-10-29 14:05:10

他的约会时间是14:05,但在我的选择中,我得到另一个较早的评论日期!

- FIDDLE

http://sqlfiddle.com/#!2/1923d2/1


@Tom解析

1 个答案:

答案 0 :(得分:3)

如果您想获得最新日期,请尝试以下方法:

<强> ORIGINAL

SELECT   activity_id, user_id, type, activity, item_id, secundary_id, MAX(date) date, 
         GROUP_CONCAT(DISTINCT user_id ) AS users 
FROM     activity
GROUP BY type, activity, item_id
ORDER BY date DESC

已编辑 - 下方将为您提供每个分组的最新记录。

SELECT   activity_id, user_id, type, activity, item_id, secundary_id, date, 
         users

FROM     activity a

         JOIN ( SELECT   MAX(activity_id) max_activity_id,
                         GROUP_CONCAT(DISTINCT user_id ) AS users
                FROM     activity
                GROUP BY type, activity, item_id
              ) AS grp ON a.activity_id = grp.max_activity_id

GROUP BY date DESC