【问题标题】:A heavy loading query not sure what's happened负载很重的查询不确定发生了什么
【发布时间】:2015-05-13 07:02:06
【问题描述】:

我有一个这样的 SQL 查询,它需要大量的加载...

不确定这里发生了什么...如果有人可以帮助我解决这个问题。

SELECT  `posts`.* FROM `posts`  
WHERE `posts`.`type` 
IN ('MySubDomainSitePost') 
AND `posts`.`aasm_state` = 'published' 
AND (published_at <= '2015-05-12 01:01:01') 
AND `posts`.`on_frontpage` = 1
AND `posts`.`is_pinned` = 0 
ORDER BY published_at DESC LIMIT 16  

【问题讨论】:

  • 查询本身非常简单 - 因此,很可能该表真的很大,而且您没有任何索引。
  • 是的!该表非常大,除了我的帖子表中的on_frontpageis_pinned,我的其他属性都有索引。那么在我查询的“所有”属性上设置索引是一个更好的解决方案?
  • 首先,将您的in 更改为=,因为您只检查一个值。其次,确保您有一个覆盖(type, aasm_state, published_at, on_frontpage,is_pinned) 的复合索引。这应该会有所帮助

标签: mysql sql ruby-on-rails database


【解决方案1】:

您需要使用explain select 检查查询性能。现在对于大型数据集,如果列没有被索引,查询的性能会很差。

从给定的查询中,您可能需要添加以下索引

alter table posts 
add index p_search_idx(type,aasm_state,published_at,on_frontpage,is_pinned);

这将提高查询速度。

确保在应用索引之前备份表。

并且不需要在查询中使用IN 它可以是

SELECT  `posts`.* FROM `posts`  
WHERE `posts`.`type` = 'MySubDomainSitePost' 
AND `posts`.`aasm_state` = 'published' 
AND (published_at <= '2015-05-12 01:01:01') 
AND `posts`.`on_frontpage` = 1
AND `posts`.`is_pinned` = 0 
ORDER BY published_at DESC LIMIT 16  

【讨论】:

  • 这个答案是我的评论。同意一切。
  • 哈看起来我们几乎同时有同样的想法deja vu
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 2012-04-10
  • 2014-07-16
相关资源
最近更新 更多