我在以下 MySQL 情况下遇到了一些问题。
我有以下表结构:
+----+---------+-----------------+------------------+--------------------------------------+------------+
| id | author | recipient | type | data | date |
+----+---------+-----------------+------------------+--------------------------------------+------------+
| 2 | 1 | 0 | added_item | { "item_id": "18" } | 1352982623 |
| 11 | 1 | 7 | started_follow | | 1353030567 |
| 9 | 1 | 0 | added_collection | { "collection_id": "18" } | 1352994561 |
| 12 | 7 | 1 | started_follow | | 1353030952 |
| 8 | 1 | 1 | started_follow | | 1352987839 |
| 14 | 1 | 0 | added_collection | { "collection_id": "19" } | 1353056624 |
| 15 | 7 | 0 | added_collection | { "collection_id": "20" } | 1353056731 |
| 16 | 1 | 7 | started_follow | | 1353057009 |
| 17 | 7 | 0 | added_item | { "item_id": "21" } | 1353057054 |
| 24 | 2 | 0 | added_image | { "image_id": "3", "item_id": "23" } | 1353419642 |
| 23 | 2 | 0 | added_item | { "item_id": "23" } | 1353419159 |
| 22 | 2 | 0 | added_collection | { "collection_id": "22" } | 1353419146 |
| 25 | 2 | 0 | added_image | { "image_id": "4", "item_id": "23" } | 1353419644 |
| 26 | 2 | 0 | added_image | { "image_id": "5", "item_id": "23" } | 1353419646 |
| 27 | 2 | 0 | added_collection | { "collection_id": "23" } | 1353419953 |
| 28 | 2 | 0 | added_item | { "item_id": "24" } | 1353419961 |
| 29 | 2 | 0 | added_image | { "image_id": "6", "item_id": "24" } | 1353419982 |
| 30 | 2 | 0 | added_item | { "item_id": "25" } | 1353420424 |
| 31 | 2 | 0 | added_image | { "image_id": "7", "item_id": "25" } | 1353420435 |
+----+---------+-----------------+------------------+--------------------------------------+------------+
我想做的是在几秒钟内对所有故事进行分组,其中author
和type
字段相同。
这是我目前正在使用的查询,但这不会返回故事的所有实例,只是每个实例第一次type
出现users
:
SELECT `activity`.`id` AS `id`
FROM `activity`
INNER JOIN `user_privacy` ON `user_privacy`.`user_id` = `activity`.`author`
WHERE (
`activity`.`author` =2
OR `activity`.`recipient` =2
)
AND `user_privacy`.`include_stream` =1
GROUP BY ROUND( UNIX_TIMESTAMP( DATE ) /300 ) , `type`
ORDER BY `activity`.`date` DESC
LIMIT 300
我在这里设置了一个 SQLFiddle 演示 > http://sqlfiddle.com/#!2/2b5f4/1。
鉴于上述数据和使用的查询,我想返回以下id
s:
- 22
- 23
- 24
- 27
- 28
- 29
- 30
- 31