Home > Back-end >  Select meta_key value from WordPress DB tabel
Select meta_key value from WordPress DB tabel

Time:01-13

I'm trying to write a SQL statement to get all of the email addresses from a WordPress DB from users within the US. Disclaimer, I have never written a SQL statement on my own. I've only modified other SQL statements. While this would be a simple SQL statement if the email and country were in separate columns of one DB table, they are stored in key/value pairs. I've attached a screenshot to illustrate. I apologize in advance if this is a stupid question.

I tried

SELECT meta_key.billing_email FROM `wp_xk_usermeta` WHERE meta_key.billing_country = "US"; 

I was hoping to get a list of all emails from people in the US.

CodePudding user response:

SQL is not correct , try using this :

SELECT meta_value
FROM wp_xk_usermeta
WHERE meta_key = 'billing_email' AND meta_value IN (
  SELECT meta_value
  FROM wp_xk_usermeta
  WHERE meta_key = 'billing_country' AND meta_value = 'US'
);

CodePudding user response:

If you have the following data in wp_xk_usermeta -

umeta_id user_id meta_key meta_value
1 1 billing_email [email protected]
2 1 billing_country US
3 2 billing_email [email protected]
4 2 billing_country US
5 3 billing_email [email protected]
6 3 billing_country UK

the following query -

SELECT `um1`.`meta_value` `billing_email`
FROM `wp_xk_usermeta` `um1`
JOIN `wp_xk_usermeta` `um2`
    ON `um2`.`user_id` = `um1`.`user_id`
    AND `um2`.`meta_key` = 'billing_country'
    AND `um2`.`meta_value` = 'US'
WHERE `um1`.`meta_key` = 'billing_email';

will return -

billing_email
[email protected]
[email protected]
  • Related