How to query data from 2 mysql tables and join the results together. My attempts keep giving me too many results

I have the need to move members from ExpressionEngine to WordPress. So far, I’ve been helped on Stackoverflow with the following query which works great and produces 696 results (the correct number of members). However I need to also export some columns from another table, and when I add them to the query, I get 484416 results (696 x 696).

Here is the original query which returns 696 results:

Read More
SELECT username AS user_login, 
username AS user_nicename, 
email AS user_email, 
url AS user_url, 
screen_name AS display_name, 
FROM_UNIXTIME(join_date) AS user_registered
FROM exp_members

Here is what I would like to do, which I tried to do with Navicat‘s Query builder. Grab the column called m_field_id_1 from the exp_member_data table and return it as user_location. This query produces 484416 results.

SELECT exp_members.username AS user_login, 
exp_members.username AS user_nicename, 
exp_members.email AS user_email, 
exp_members.url AS user_url, 
exp_members.screen_name AS display_name, 
FROM_UNIXTIME(join_date) AS user_registered, 
exp_member_data.m_field_id_1 AS user_location // here is the m_field_id_1
FROM exp_members, exp_member_data

How do I properly combine these 2 tables so there’s still only 696 returned results but with the additional column? Thanks

Related posts

Leave a Reply

1 comment

  1. You need a JOIN condition between the tables, or you get a cartesian product of the two (all rows of table1 multiplied by all rows of table2, or 696^2 in this case).

    SELECT
      exp_members.username AS user_login, 
      exp_members.username AS user_nicename, 
      exp_members.email AS user_email, 
      exp_members.url AS user_url, 
      exp_members.screen_name AS display_name, 
      FROM_UNIXTIME(join_date) AS user_registered, 
      exp_member_data.m_field_id_1 AS user_location
    FROM
      exp_members
      JOIN exp_member_data 
        /* ON clause specifies the relation between the two tables */
        ON exp_members.username = exp_member_data.username
    

    The above assumes there’s a column in exp_member_data called username which maps to exp_member.username. If instead there is an id column between them, use it instead as in:

      JOIN exp_member_data ON exp_members.member_id = exp_member_data.member_id