在mysql中多次连接一个表

时间:2015-04-24 08:51:34

标签: php mysql

我有两个表用于用户和组成员信息。我将groupmember表格中的两个用户ID存储为group_userid,将另一个用户ID存储为group_memberid。我想将用户表与group_useridgroup_memberi d联系起来。我试过这个问题:

SELECT U.*, 
  S1.user_id as folusrid,
  S1.first_name,
  S1.last_name, 
  S2.user_id as follwginuserid,
  S2.first_name,
  S2.last_name 
FROM tbl_groupmemebers U 
JOIN tbl_user S1 ON (S1.user_id = U.group_userid) 
JOIN tbl_user S2 ON (S2.user_id = U.group_memberid) 
WHERE U.group_id = '2'

得到了结果但结果却让我回到了同一行:

id    group_id    group_userid    group_memberid    group_joindate        folusrid    first_name        last_name    follwginuserid    first_name    last_name
3        2            18                11          2015-04-24 12:02:36     18        Mohammadshoaib    Swichmann           11           Clemen      Swichmann

我希望结果分成两列。

1 个答案:

答案 0 :(得分:0)

试试这个UNION

(
  SELECT U.*, 
    S1.user_id as user_id,
    S1.first_name,
    S1.last_name,
    'group_userid' as data_type
  FROM tbl_groupmemebers U 
  JOIN tbl_user S1 ON (S1.user_id = U.group_userid) 
  WHERE U.group_id = '2'
)
UNION ALL
(
  SELECT U.*, 
    S2.user_id as user_id,
    S2.first_name,
    S2.last_name,
    'group_userid' as data_type
  FROM tbl_groupmemebers U
  JOIN tbl_user S2 ON (S2.user_id = U.group_memberid) 
  WHERE U.group_id = '2'
);

这将为每个U.group_userid提供一条记录,为每个U.group_memberid提供一条记录。使用' data_type'列(最后一个),以确定哪一个是什么。