如何从2个mysql表中查询数据并将结果连接在一起。我的尝试一直给我太多结果

时间:2012-04-19 01:54:52

标签: mysql wordpress expressionengine

我需要将成员从ExpressionEngine移动到WordPress。到目前为止,我已经在Stackoverflow上获得了以下查询的帮助,该查询效果很好并产生了696个结果(正确的成员数)。但是我还需要从另一个表中导出一些列,当我将它们添加到查询中时,我得到484416个结果(696 x 696)。

以下是返回696结果的原始查询:

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

以下是我想要做的事情,我尝试使用Navicat的“查询”构建器。从m_field_id_1表中抓取名为exp_member_data的列,并将其作为user_location返回。此查询产生484416个结果。

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

如何正确组合这两个表,以便仍然只有696个返回的结果,但附加列?感谢

1 个答案:

答案 0 :(得分:2)

表之间需要JOIN条件,或者你得到两者的笛卡尔乘积(table1的所有行乘以table2的所有行,或者在这种情况下为696 ^ 2)。

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

以上假设exp_member_data中有一个名为username的列映射到exp_member.username。如果它们之间有一个id列,请改为使用它:

  JOIN exp_member_data ON exp_members.member_id = exp_member_data.member_id