如何优化此查询并使其执行得更快? [关闭]
Posted
技术标签:
【中文标题】如何优化此查询并使其执行得更快? [关闭]【英文标题】:How can I optimize this query and make it execute faster? [closed] 【发布时间】:2013-01-05 07:11:19 【问题描述】:如何通过此查询获得更快的结果?
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 个条目。因此,显示结果需要时间。
【问题讨论】:
你不能使用 JOIN 代替子查询吗?另外,确保所有相关字段都已编入索引,例如meta_key
、post_id
、term_taxonomy_id
...
您需要向我们展示表和索引定义。 诊断慢查询需要完整的表和索引定义,而不仅仅是描述或解释。也许您的表格定义不佳。也许索引没有正确创建。也许您认为您在该列上没有索引。没有看到表和索引定义,我们无法分辨。
这看起来很像一堆 WordPress 表和列名?
【参考方案1】:
使用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
【讨论】:
【参考方案2】:试试这个:
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;
【讨论】:
以上是关于如何优化此查询并使其执行得更快? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何通过优化 Python 中的 GPU 使用率将视频处理速度提高 5 倍(教程含源码)
Oracle 执行计划:成本与实际问题:成本较高的查询运行得更快