4表连接的MySQL表索引

时间:2012-07-30 15:16:14

标签: mysql optimization indexing

我有四张桌子:

activity (activity_id (PRIMARY), item_id, geolat, geolng, user_id, created_at)
users (user_id (PRIMARY), user_name, first_name, last_name, user_banned)
items (item_id (PRIMARY), item_name)
ratings (item_id (PRIMARY), avg_rating_score)

我想运行以下查询:

SELECT item_name, count(distinct activity.user_id) as distinct_user_count, ratings.avg_rating_score
FROM activity
INNER JOIN users on activity.user_id = users.user_id
INNER JOIN items on activity.item_id = items.item_id
INNER JOIN ratings on activity.item_id = ratings.item_id
WHERE activity.user_id != 1
AND (activity.geolat BETWEEN 'XXXXX' and 'XXXX' and activity.geolng BETWEEN 'XXXX' and 'XXXX') 
AND (users.user_banned = 0)
GROUP by activity.item_id
HAVING distinct_user_count >= 5
ORDER by avg_rating_score DESC
LIMIT 0,5

我正在努力争取这次加入的正确索引。现在我有:

ALTER TABLE activity ADD INDEX (user_id)
ALTER TABLE activity ADD INDEX (item_id)
ALTER TABLE activity ADD INDEX (geolat)
ALTER TABLE activity ADD INDEX (geolng)
ALTER TABLE users ADD INDEX (user_banned)

查询的目标是获取用户1从未添加的项目列表(在lat / lng半径内),在用户1的本地区域中至少发生过5次,按照评级的降序排序该项目,最后不包括任何被禁止的用户。

这是最好的方法吗?有没有更好的方法来解决这个问题?上面列出的索引运行得非常慢。

0 个答案:

没有答案