为什么我的嵌套查询会使SQL服务器变慢?

时间:2014-03-12 12:15:07

标签: php mysql sql

以下是我的查询。从不到30个结果中抽取12个结果需要8秒钟。这里发生了什么?服务器非常快,有一些非常复杂的查询,但不是这个......

SELECT meta_value FROM wp_postmeta where post_id IN
  (SELECT meta_value from wp_postmeta WHERE post_id IN 
     (select id from wp_posts WHERE post_type = 'ads') 
      AND meta_key like 'image1')

2 个答案:

答案 0 :(得分:1)

在您的情况下,对WHERE中的每一行执行select。而是将其放在FROM部分中。像这样。

SELECT meta_value 
FROM wp_postmeta t1
     JOIN wp_postmeta t2 ON t2.meta_value=t1.post_id AND meta_key like 'image1'
     JOIN wp_posts t3 ON t3.id=t1.post_id AND post_type = 'ads' 

答案 1 :(得分:0)

如果您不需要通配符,我会将LIKE更改为=(等于),具体取决于可能会产生影响的数据库和查询优化程序。另外,为什么要将SELECT meta_value嵌套两次?查询不应该是(没有外部子句):

SELECT meta_value FROM wp_postmeta WHERE meta_key='image1' AND post_id IN (
SELECT id FROM wp_posts WHERE post_type = 'ads') 

SELECT a.meta_value FROM wp_postmeta a WHERE a.meta_key='image1' AND EXISTS (
SELECT * FROM wp_posts b WHERE b.post_type = 'ads' AND b.id=a.post_id) 

SELECT a.meta_value FROM wp_postmeta a JOIN wp_posts b ON b.id=a.post_id WHERE 
a.meta_key='image1' AND b.post_type = 'ads'
祝你好运!