更新:表和索引定义
desc activities;x
+----------------+--------------+------+-----+---------+
| Field | Type | Null | Key | Default |
+----------------+--------------+------+-----+---------+
| id | int(11) | NO | PRI | NULL |
| trackable_id | int(11) | YES | MUL | NULL |
| trackable_type | varchar(255) | YES | | NULL |
| owner_id | int(11) | YES | MUL | NULL |
| owner_type | varchar(255) | YES | | NULL |
| key | varchar(255) | YES | | NULL |
| parameters | text | YES | | NULL |
| recipient_id | int(11) | YES | MUL | NULL |
| recipient_type | varchar(255) | YES | | NULL |
| created_at | datetime | NO | | NULL |
| updated_at | datetime | NO | | NULL |
+----------------+--------------+------+-----+---------+
show indexes from activities;
+------------+------------+-----------------------------------------------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type |
+------------+------------+-----------------------------------------------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+
| activities | 0 | PRIMARY | 1 | id | A | 7263 | NULL | NULL | | BTREE |
| activities | 1 | index_activities_on_trackable_id_and_trackable_type | 1 | trackable_id | A | 7263 | NULL | NULL | YES | BTREE |
| activities | 1 | index_activities_on_trackable_id_and_trackable_type | 2 | trackable_type | A | 7263 | NULL | NULL | YES | BTREE |
| activities | 1 | index_activities_on_owner_id_and_owner_type | 1 | owner_id | A | 7263 | NULL | NULL | YES | BTREE |
| activities | 1 | index_activities_on_owner_id_and_owner_type | 2 | owner_type | A | 7263 | NULL | NULL | YES | BTREE |
| activities | 1 | index_activities_on_recipient_id_and_recipient_type | 1 | recipient_id | A | 2421 | NULL | NULL | YES | BTREE |
| activities | 1 | index_activities_on_recipient_id_and_recipient_type | 2 | recipient_type | A | 3631 | NULL | NULL | YES | BTREE |
+------------+------------+-----------------------------------------------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+
select count(id) from activities;
+-----------+
| count(id) |
+-----------+
| 7117 |
+-----------+
这是我当前查询的样子:
SELECT act.*, group_concat(act.owner_id order by act.created_at desc) as owner_ids
FROM (select * from activities order by created_at desc) as act
INNER JOIN users on users.id = act.owner_id
WHERE (users.city_id = 1 and act.owner_type = 'User')
GROUP BY trackable_type, recipient_id, recipient_type
order by act.created_at desc
limit 20 offset 0;
做解释
我玩过这个查询很多,包括索引等。有没有办法优化这个查询?