0

我有一个跨 2000 万条记录表的简单查询,我需要一个索引来改进以下查询的 select 语句:

 SELECT count(item_id), count(distinct user_id)
 FROM activity
 INNER JOIN item on item.item_id = activity.item_id
 WHERE item.item_id = 3839 and activity.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)

我有一个索引:

activity - activity_id (PRIMARY), item_id, created_at - All Single Index
item - item_id (PRIMARY)

对于具有大量内容(如 600k)的项目,运行查询需要 4-5 秒。

有什么建议吗?

4

1 回答 1

0

If there is a FOREIGN KEY constraint from activity to item (and assuming that user_id is in table activity), then your query is equivalent to:

SELECT COUNT(*), COUNT(DISTINCT user_id)
FROM activity
WHERE item_id = 3839 
  AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) ;

which should be more efficient as it has to get data from only one table or just one index. An index on (item_id, created_at, user_id) would be useful.

于 2013-02-07T23:39:47.970 回答