优化mysql查询 - 许多内部联接

时间:2012-05-23 20:54:14

标签: mysql wordpress

我正在尝试在wordpress中优化以下查询,因为返回结果需要将近一分半钟。表关系如下图所示:

enter image description here

SELECT SQL_CALC_FOUND_ROWS wp_posts . *
    FROM wp_posts
       INNER JOIN wp_term_relationships 
        ON (wp_posts.ID = wp_term_relationships.object_id)
       INNER JOIN wp_term_relationships AS tt1 
        ON (wp_posts.ID = tt1.object_id)
       INNER JOIN wp_term_relationships AS tt2 
        ON (wp_posts.ID = tt2.object_id)
       INNER JOIN wp_term_relationships AS tt3 
        ON (wp_posts.ID = tt3.object_id)
       INNER JOIN wp_term_relationships AS tt4 
        ON (wp_posts.ID = tt4.object_id)
    WHERE 1 = 1
        AND (
            wp_term_relationships.term_taxonomy_id IN (25) 
            OR tt1.term_taxonomy_id IN (26) 
            OR tt2.term_taxonomy_id IN (16) 
            OR tt3.term_taxonomy_id IN (17) 
            OR tt4.term_taxonomy_id IN (18)
        ) 
        AND wp_posts.post_type IN ('product') 
        AND (wp_posts.post_status = 'publish')
    GROUP BY wp_posts.ID
    ORDER BY wp_posts.post_title ASC
    LIMIT 0 , 15

3 个答案:

答案 0 :(得分:1)

我不明白wp_term_relationships表中所有内部联接的重点,当你看到它正在寻找一系列值时。以下不会执行相同的操作并执行得更快吗?

SELECT SQL_CALC_FOUND_ROWS wp_posts . *
    FROM wp_posts
       INNER JOIN wp_term_relationships 
        ON (wp_posts.ID = wp_term_relationships.object_id)
    WHERE wp_term_relationships.term_taxonomy_id IN (25, 26, 16, 17, 18) 
        AND wp_posts.post_type = 'product' 
        AND wp_posts.post_status = 'publish'
    GROUP BY wp_posts.ID
    ORDER BY wp_posts.post_title ASC
    LIMIT 0 , 15

答案 1 :(得分:0)

试试这个。我认为这会更快。

SELECT SQL_CALC_FOUND_ROWS wp_posts . *
FROM wp_posts,
     wp_term_relationships 
WHERE wp_posts.ID = wp_term_relationships.object_id
AND wp_term_relationships.term_taxonomy_id IN (25,26,16,17,18)
AND wp_posts.post_type = 'product' 
AND wp_posts.post_status = 'publish'
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_title ASC
LIMIT 0 , 15

你不需要那么多INNER JOINS。

答案 2 :(得分:0)

如果多个联接背后的想法是检索相应的term_taxonomy_id 25和26以及17的帖子,...(意思是所有条款而不是对于其中任何一个),你可以只用一个JOIN重用KayakJim的答案并添加一个HAVING子句,只保留与所有5个术语匹配的行。

这是修改过的查询:

SELECT SQL_CALC_FOUND_ROWS wp_posts . *
    FROM wp_posts
       INNER JOIN wp_term_relationships 
        ON (wp_posts.ID = wp_term_relationships.object_id)
    WHERE wp_term_relationships.term_taxonomy_id IN (25, 26, 16, 17, 18) 
        AND wp_posts.post_type = 'product' 
        AND wp_posts.post_status = 'publish'
    GROUP BY wp_posts.ID
    HAVING count(*)=5
    ORDER BY wp_posts.post_title ASC
    LIMIT 0 , 15