0

I need to get one meta_value from wp_postmeta and I can do it with one category but I'm having problem when using another one.

I have:

SELECT wp_posts.ID, wp_postmeta.meta_value FROM wp_postmeta
LEFT JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id
LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
LEFT JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE wp_postmeta.meta_key = '_application'
AND wp_term_taxonomy.term_id = '14'

and my results are:

ID | meta_value
91 | email@email.com
99 | email3@email.com

when I change last line wp_term_taxonomy.term_id = '14' to wp_term_taxonomy.term_id = '31' i will get:

ID | meta_value
91 | email@email.com
95 | email2@email.com

Problem starts when I use 2 categories

SELECT wp_posts.ID, wp_postmeta.meta_value FROM wp_postmeta
LEFT JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id
LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
LEFT JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE wp_postmeta.meta_key = '_application'
AND wp_term_taxonomy.term_id = '14'
AND wp_term_taxonomy.term_id = '31'

then I will get nothing

MySQL returned an empty result set (i.e. zero rows).

and I should get:

ID | meta_value
91 | email@email.com

How can I use both categories (term_id = '14' and term_id = '31' ) at the same time in one query so my results will show only meta_values for posts that are in both categories?

0

ok, I was close and I have solution:

SELECT wp_posts.ID, wp_postmeta.meta_value FROM wp_postmeta    
INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)  
INNER JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) 
WHERE 1=1 
AND wp_postmeta.meta_key = '_application'
AND ( wp_term_relationships.term_taxonomy_id IN (31) 
  AND 
  tt1.term_taxonomy_id IN (14)
) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.