0

I am trying to query two meta keys at once using my code:

SELECT * FROM wp_postmeta

WHERE meta_key = "listing_location_enabled"
AND meta_value = "yes"

AND meta_key = "listing_location_country"
AND meta_value = "INDIA"

But is not showing any results. Is my query correct?

1
  • Try this: SELECT * FROM WP_POSTMETA WHERE (META_KEY = "LISTING_LOCATION_ENABLED" AND META_VALUE = "YES") OR( META_KEY = "LISTING_LOCATION_COUNTRY" AND META_VALUE = "INDIA")
    – Abimanyu
    Commented Apr 13, 2022 at 11:22

1 Answer 1

1

No, your query is not correct. (Those meta tables are a notorious pain in the xxx neck to use correctly.) You need this query pattern. It joins wp_postmeta to itself.

SELECT lle.post_id,
       lle.meta_value listing_location_enabled.
       llc.meta_value listing_location_country
 
  FROM wp_postmeta lle
  JOIN wp_postmeta llc  ON lle.post_id = llc.post_id
 WHERE lle.meta_key = 'listing_location_enabled'
   AND lle.meta_value = 'yes'
   AND llc.meta_key = 'listing_location_country'
   AND llc.meta_value = 'INDIA'

Or, better yet if you're writing code for WordPress, use its WP_Meta_Query facility.

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'lle' => array(
            'key' => 'listing_location_enabled',
            'value' => 'yes',
        ),
        'llc' => array(
            'key' => 'listing_location_country',
            'value' => 'INDIA',
        ), 
    )
) );
1
  • Wordpress Sql is needed at the moment, i know using wp_query or get_posts. Thanks
    – webifo
    Commented Apr 13, 2022 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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