按日期时间排序时,Mysql查询太慢

时间:2017-10-16 08:37:23

标签: mysql datetime indexing

我有一张大约10k行的表格。我在sql下运行但是需要花费太多时间(~4秒):

SELECT
        ID, post_date, post_title, post_name, pc.post_view,
        t.name AS post_category,
        pm2.meta_value AS post_image
    FROM wp_posts p
        INNER JOIN wp_term_relationships tr ON p.ID = tr.object_id
        INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy='category'
        INNER JOIN wp_terms t ON tt.term_id = t.term_id AND (t.name='My Posts' OR t.name='HOT posts')
        LEFT JOIN post_counter pc ON p.ID = pc.post_id
        LEFT JOIN wp_postmeta pm ON pm.post_id = p.ID AND pm.meta_key = '_thumbnail_id'
        LEFT JOIN wp_postmeta pm2 ON pm.meta_value = pm2.post_id AND pm2.meta_key = '_wp_attached_file'
    WHERE p.post_status = 'publish' AND p.post_type = 'post'
    ORDER BY FIELD(t.name, 'HOT posts', 'My Posts'), post_date DESC
    LIMIT 14

如果我删除“按post_date排序”,一切都很好。运行只需0.05秒。

我在CREATE INDEX和ADD INDEX中添加了一些索引(我不知道它们之间有什么区别):

CREATE INDEX ix_type_date ON wp_posts (post_type, post_date)

ALTER TABLE wp_posts ADD INDEX ix_status_type_date (post_status,post_type,post_date)

然后将这些索引与USE INDEX和FORCE INDEX一起使用(我也不知道它们之间有什么区别):

    ...FROM wp_posts p USE INDEX (ix_type_date)...

OR

    ...FROM wp_posts p FORCE INDEX (ix_status_type_date)...

我仍然记录,但加载时间增加到7-8秒。

真的需要你的帮助! 先谢谢!

修改

表的结构

ID  bigint(20)  No           
post_author bigint(20)  No  0        
post_date   datetime    No  0000-00-00 00:00:00          
post_date_gmt   datetime    No  0000-00-00 00:00:00          
post_content    longtext    No           
post_title  text    No           
post_excerpt    text    No           
post_status varchar(20) No  publish          
comment_status  varchar(20) No  open         
ping_status varchar(20) No  open         
post_password   varchar(255)    No           
post_name   varchar(200)    No           
to_ping text    No           
pinged  text    No           
post_modified   datetime    No  0000-00-00 00:00:00          
post_modified_gmt   datetime    No  0000-00-00 00:00:00          
post_content_filtered   longtext    No           
post_parent bigint(20)  No  0        
guid    varchar(255)    No           
menu_order  int(11) No  0        
post_type   varchar(20) No  post         
post_mime_type  varchar(100)    No           
comment_count   bigint(20)  No  0 

1 个答案:

答案 0 :(得分:0)

你想要"热门帖子"首先,然后"我的帖子"?并且可能会少于14个Hotties,并且有很多"我的帖子"?

一个笨拙的解决方案是

( SELECT ... name='HOT posts' ORDER BY post_date DESC  LIMIT 14 )
UNION ALL
( SELECT ... name='My Posts'  ORDER BY post_date DESC  LIMIT 14 )
ORDER BY field(...), post_date DESC  LIMIT 14

请注意,有可能快速找到每个类别的最新14个,然后快速重新排列28以获得所需的14个。

对于多对多表格,请参阅here了解如何改善其效果。 (默认WP效率很低。)

如果您需要进一步讨论,请提供EXPLAIN SELECT ...SHOW CREATE TABLE