0

我有这张桌子:

activity - activity_id - (INT) PRIMARY, 
            item_id (INT),
            user_id (INT)
            lat (FLOAT), 
            lng (FLOAT), 
            created_at (DATETIME)  

我想运行以下查询:

SELECT item_id, count(distinct user_id) as c_c
FROM activity
WHERE (lat BETWEEN X and X and lng BETWEEN X and X)
and created_at >= DATE(NOW(), INTERVAL 15 DAY)
GROUP by item_id
ORDER by c_c desc
LIMIT 10

我以为我对以下字段做了索引:

lat,
lng,
created_at,
bid

那 - 它会运行得非常快,但它仍然运行缓慢。这里的最佳索引是多少?我是否在其中包含了 user_id?

任何建议将不胜感激。

更新:

这是解释:

+----+-------------+----------+-------+-----------------------------------------+---------+---------+------+-------+----------------------------------------------+
| id | select_type |  table   | type  |              possible_keys              |   key   | key_len | ref  | rows  |                    Extra                     |
+----+-------------+----------+-------+-----------------------------------------+---------+---------+------+-------+----------------------------------------------+
|  1 | SIMPLE      | activity | index | lat,created_lat_lng,created_at,lat_user | item_id |       4 | NULL | 51510 | Using where; Using temporary; Using filesort |
+----+-------------+----------+-------+-----------------------------------------+---------+---------+------+-------+----------------------------------------------+

表上的索引:

+-----------------+----------------------+
|      Name       |       Columns        |
+-----------------+----------------------+
| lat             | lat, lng             |
| created_lat_lng | lat, lng, created_at |
| created_at      | created_at           |
| lat_user        | lat,lng,user_id,item |
| item_id         | item_id              |
+-----------------+----------------------+
4

0 回答 0