简体   繁体   中英

Why does my nested query slow the SQL server so much?

Below is my query. It took 8 seconds to draw 12 results from less than 30 possible. What's going on here? The server is REALLY fast with some very complex queries, but not this...

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')

In your case the select is executed for each row in WHERE. Place it in the FROM section instead. Like this.

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' 

If you don't need wildcards I would change LIKE to = (equals), depending on the database and query optimizer, that might have an impact. Also, why did you nest the SELECT meta_value twice? Shouldn't the query be (without the outer clause):

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

or

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) 

or

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'

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM