大表的 ORDER BY 优化

5 mysql optimization

我目前正在汇总来自不同社交网络的帖子。目前我有来自 Facebook、Twitter、Youtube、Instagram 和 Pinterest 的 50-1 亿个帖子。

考虑一张桌子 posts

posts
{
    id  int(11),
    user_id  int(11),
    url varchar(256), 
    image varchar(256), 
    source int(11),  // Social Network Source 
    created bigint(20), // Publish time of the post 
    visible int(1) // Public or Private Posts
}
Run Code Online (Sandbox Code Playgroud)

使用 InnoDB

索引:

primary key on id
user_id,source
user_id,created
Run Code Online (Sandbox Code Playgroud)

空间使用

Type    Usage 
Data    45,876.0    MiB
Index   4,959.0 MiB
Total   50,835.0    MiB
Run Code Online (Sandbox Code Playgroud)

使用具有 7.5 GB RAM 的 Amazon RDS。

我正在执行的查询如下

select id 
from posts 
where user_id={user_id} 
  and visible=1  
order by created desc 
  LIMIT 20 ;


select id 
from posts 
where user_id={user_id} 
  and source={your_network} 
  and visible=1 
order by created desc 
  LIMIT 20 ;
Run Code Online (Sandbox Code Playgroud)

对于帖子超过 50 万的用户,有时我的查询需要很长时间。

我已经运行了解释,你可以看到下面的结果

EXPLAIN SELECT id
FROM  `posts` 
WHERE user_id =123529745 and source=1 and visible=1
ORDER BY created DESC 
LIMIT 20

id    select_type       table   type    possible_keys   key     key_len ref     rows    Extra 
1       SIMPLE          posts   ref     user_id_2,user_id_4,user_id_3,created   created 4       const   954174  Using where; Using index

id    select_type       table   type    possible_keys   key     key_len ref     rows    Extra 
1       SIMPLE          posts   ref     user_id_2,user_id_4,user_id_3,created   created 4       const   742308  Using where;
Run Code Online (Sandbox Code Playgroud)

你能给我建议任何优化吗?

Gor*_*off 5

这是您的查询:

SELECT id
FROM  `posts` 
WHERE user_id =123529745 and source=1 and visible=1
ORDER BY created DESC
Run Code Online (Sandbox Code Playgroud)

您只在 中进行相等比较where,然后按 进行排序created

单个索引: posts(user_id, source, visible, created, id)应该允许整个查询仅由索引满足——首先找到正确的行,然后按它们排序,然后获取 id。