PHP / MySQL多表连接/联合

时间:2011-07-10 06:41:10

标签: mysql

我是MySQL的新手,我很难从多个表中选择项目。

我有3个表(users,groups,group_members)。以下是每个表格的内容:

  • 用户:user_id,user_email,user_name
  • groups:group_id,group_name
  • group_members:group_id,user_id

鉴于user_id,我想在一个查询中找到user_emailuser_namegroup_idgroup_name。问题是用户可以一次分成3组,所以在我的查询中,我需要从group_members和groups表中获取三行。任何帮助将不胜感激,下面是我最好的两次尝试。

SELECT groups.group_id, groups.group_name, users.user_email, users.user_name 
     FROM groups, membership, users
     WHERE membership.user_id=<user id> AND 
           membership.group_id = groups.group_id LIMIT 3;

SELECT groups.group_id, groups.group_name, users.user_email, users.user_name 
     FROM groups 
         LEFT JOIN membership ON groups.group_id = membership.group_id 
         LEFT JOIN users ON membership.user_id = users.user_id 
     WHERE (users.user_id = <user id>);

我能够获得group_id和group_name的一行但不是全部3.感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

使用此查询:

    SELECT groups.group_id, groups.group_name, users.user_email, users.user_name 
    FROM groups, membership, users 
    WHERE users.user_id=%s AND
          membership.user_id=users.user_id AND 
          membership.group_id = groups.group_id 
    LIMIT 3

答案 1 :(得分:0)

SELECT groups.group_id, groups.group_name, users.user_email, users.user_name 
FROM users 
     left inner join membership on membership.user_id = users.user_id
     inner join groups.group_id on groups.group_id = membership.group_id
Where users.user_id = %user_id%

问题在于,您将获得尽可能多的具有重复电子邮件和用户名的行,就像许多用户所属的组一样。如果您只需要一次用户名和电子邮件,以及一个组列表,那么它将是2个请求。

但是,如果用户不属于任何群组,这也会在group_id和group_name中返回带有空值的用户名和电子邮件。