我有以下表格:
items (item_id (PRIMARY), item_name)
activity (activity_id (PRIMARY), item_id (INT), user_id (INT), lat (FLOAT), lng (FLOAT), created_at)
我想做以下查询:
SELECT
i.item_id,
i.item_name,
count(distint a.user_id) as total_count
FROM activity as a
INNER JOIN item as i
on a.item_id = i.item_id
WHERE (a.lat BETWEEN XXXXXXX
and XXXXXXX
and a.lng BETWEEN XXXXXXX
and XXXXXXX)
and created_at >= DATE_SUB(NOW(), INTERVAL 5 DAY)
GROUP by a.bid
ORDER BY RAND()
LIMIT 5
这是对 3-5 百万记录表的繁重查询,即使我有活动索引:
item_index (item_id, lat, lng, created_at)
这不会在 EXPLAIN 中使用,它只是默认为“item_id”。我想我要问的是 - 需要添加哪些索引才能使此查询快速运行,或者我可以进行优化吗?