David McClave
David McClave

Reputation: 167

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

Upvotes: 0

Views: 99

Answers (2)

Fredrik Johansson
Fredrik Johansson

Reputation: 3535

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!

Upvotes: 0

StanislavL
StanislavL

Reputation: 57421

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' 

Upvotes: 1

Related Questions