如何优化此查询并使其执行速度更快?

时间:2013-01-05 07:11:20

标签: mysql sql select query-optimization

如何通过此查询获得更快的结果?

SELECT
    post_id
FROM
    wp_postmeta
WHERE
    meta_key='wpcf-cooler-name' AND (
        post_id IN (
            SELECT 
                post_id
            FROM
                wp_postmeta
            WHERE
                meta_key='wpcf-cooler-name' AND
                meta_value LIKE '%sosa%' AND (
                    post_id IN (
                        SELECT
                            object_id AS 'post_id'
                        FROM
                            wp_term_relationships
                        WHERE 
                            term_taxonomy_id=227
                    )
                ) AND (
                    post_id IN (
                        SELECT
                            ID AS 'post_id'
                        FROM
                            wp_posts
                        WHERE 
                            post_type='cooler' AND
                            post_status='publish'
                    )
                )
        )
    ) ORDER BY meta_value ASC

我的数据库有超过15000个条目。因此,显示结果需要时间。

2 个答案:

答案 0 :(得分:3)

使用WHERE条件:

SELECT
  post.id
FROM
  wp_posts as post, wp_postmeta as postmeta, wp_term_relationships as relationships
WHERE
  postmeta.meta_key='wpcf-cooler-name'
  AND postmeta.meta_value LIKE '%sosa%'
  AND relationships.object_id = post.post_id
  AND relationships.term_taxonomy_id = 227
  AND post.ID = postmeta.post_id
  AND post.post_type = 'cooler'
  AND post.post_status='publish'
ORDER BY postmeta.meta_value ASC

答案 1 :(得分:0)

试试这个:

SELECT wp.post_id 
FROM wp_postmeta wp 
INNER JOIN (SELECT object_id AS 'post_id' 
            FROM wp_term_relationships 
            WHERE term_taxonomy_id = 227 
        UNION  
            SELECT ID AS 'post_id' 
            FROM wp_posts 
            WHERE post_type = 'cooler' AND post_status = 'publish') A ON wp.post_id = A.post_id
WHERE wp.meta_key = 'wpcf-cooler-name' AND wp.meta_value LIKE '%sosa%' 
ORDER BY wp.meta_value;