Car*_*son 4 mysql database optimization
我有一个博客文章表,每个都有一个外键回到它的作者.此表中有<15,000个条目.此查询扫描超过19,000行(每个EXPLAIN
),需要一个文件排序(可能是常规的MySQL行为),并需要超过400毫秒才能返回5行.可能是因为WHERE
用于检查项目是否实际发布的复杂程度.
最亲爱的Stack Overflow,我如何能够控制这个查询?
注意:虽然此标准可能需要简化,但所有条件都是必需的.
SELECT `blog_post.id`,
`blog_post.title`,
`blog_post.author_id`,
`blog_post.has_been_fact_checked`,
`blog_post.published_date`,
`blog_post.ordering`,
`auth_user.username`,
`auth_user.email`
FROM `blog_post`
INNER JOIN `auth_user`
ON (`blog_post`.`author_id` = `auth_user`.`id`)
WHERE (`blog_post`.`is_approved` = True AND
`blog_post`.`has_been_fact_checked` = True AND
`blog_post`.`published_date` IS NOT NULL AND
`blog_post`.`published_date` <= '2010-10-25 22:40:05' )
ORDER BY `blog_post`.`published_date` DESC,
`blog_post`.`ordering` ASC,
`blog_post`.`id` DESC
LIMIT 5
Run Code Online (Sandbox Code Playgroud)
除了PK,我在表上有以下索引:
idx_published_blog_post -> blog_post(is_approved, has_been_fact_checked, published_date)
idx_pub_date -> blog_post(published_date)
Run Code Online (Sandbox Code Playgroud)
输出EXPLAIN
如下所示:
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: blog_post
type: ref
possible_keys: blog_post_author_id,idx_published_blog_post,idx_pub_date
key: idx_published_blog_post
key_len: 4
ref: const,const
rows: 19856
Extra: Using where; Using filesort
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: auth_user
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: blog.blog_post.author_id
rows: 1
Extra: Using index
2 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
旁注:2010-10-25 22:40:05
只是执行此查询的代码生成的日期.
非常感谢任何和所有的帮助!
MySQL
不支持ASC/DESC
索引中的子句.
您需要创建一个单独的列reverse_ordering
,并将其值设置为-ordering
(假设这ordering
是一个数值)
然后,您可以创建以下索引:
CREATE INDEX ix_blogpost_a_c_p_ro_id ON blog_post (is_approved, has_been_fact_checked, published_date, reverse_ordering, id)
Run Code Online (Sandbox Code Playgroud)
并重写您的查询:
SELECT `blog_post.id`,
`blog_post.title`,
`blog_post.author_id`,
`blog_post.has_been_fact_checked`,
`blog_post.published_date`,
`blog_post.ordering`,
`auth_user.username`,
`auth_user.email`
FROM `blog_post`
INNER JOIN `auth_user`
ON `blog_post`.`author_id` = `auth_user`.`id`
WHERE `blog_post`.`is_approved` = 1 AND
`blog_post`.`has_been_fact_checked` = 1 AND
`blog_post`.`published_date` <= '2010-10-25 22:40:05'
ORDER BY `blog_post`.`published_date` DESC,
`blog_post`.`reverse_ordering` DESC,
`blog_post`.`id` DESC
LIMIT 5
Run Code Online (Sandbox Code Playgroud)
你可以摆脱IS NULL
检查,因为不平等条件意味着它.
更新:
您可能还想阅读这篇文章: