1

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

在此处输入图像描述

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
4

3 回答 3

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
于 2012-05-23T21:04:58.413 回答
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。

于 2012-05-23T21:01:18.027 回答
0

If the idea behind the multiple joins was to retrieve the posts with a corresponding term_taxonomy_id of 25 and also 26 and also 17,... (meaning ALL of the terms as opposed to ANY of them), you can reuse KayakJim's answer with only one JOIN and add an HAVING clause, keeping only the rows that matched with all of the 5 terms.

Here would be the modified query:

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
于 2012-05-23T23:30:14.087 回答