Ready to get started?Download WordPress


JOIN tables in wpdb not working (2 posts)

  1. holidaymaine
    Posted 3 years ago #

    I have a a lot of users on my site and many of them have the same last names. I am trying to get their emails by their last name. WP stores emails in the users table and user names in the usermeta and I have been trying to use JOIN to get what I want, but I don't understand how it works and I am about to give up for the day. This is what i have after 4.5 hours.

    $usersemails = $wpdb->get_results("SELECT users.user_email, usermeta.meta_value FROM $wpdb->users LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE user_status = '0' AND meta_value = 'Smith'");

    Any help is appreciated, so can you please help? Thanks.

  2. s_ha_dum
    Posted 2 years ago #

    Unless you have a custom table structure 'users' is not a valid WordPress table name, nor is 'usermeta'. The table names are 'wp_users' and 'wp_usermeta' respectively. Your query should be, barring typos:

    "SELECT {$wpdb->users}.user_email, {$wpdb->usermeta}.meta_value FROM $wpdb->users LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE user_status = '0' AND meta_value = 'Smith'"

Topic Closed

This topic has been closed to new replies.

About this Topic