需要在select语句中连接子查询的结果

时间:2010-10-08 21:53:19

标签: mysql

我有三张桌子

Table1: Users
Columns: User_ID (int), FirstName, LastName....
Values
1            Jane        Doe
2            John        Doe
3            Mike        Smith

Table2: User_Groups
Columns: User_ID (int), Group_ID(int)
Values:
Row1: 1          2  
Row2: 1          3
Row3: 2          1
Row4: 2          3
Row5: 3          1

Table3: Groups
Columns: Group_ID (int), GroupName(varchar)
Values
Row1: 1         Admin
Row2: 2         Power User
Row3: 3         Developer

我想创建一个可以按以下方式返回结果的查询: ** RESULT

UserID GroupNames
Row1: 1      Power User, Developer
Row2: 2      Admin, Developer
Row3: 3      Admin

在SQL Server中 - 我能够使用以下内容实现它:

SELECT User_ID,
  SUBSTRING( 
     replace( 
         replace( 
     (SELECT Groups.GroupName
  FROM User_Groups, Groups 
  where groups.Group_ID = 
                  User_Groups.Group_ID AND
                User_Groups.User_ID =Users.User_ID
          FOR XML PATH('') )
          ,'<GROUPNAME>',', ')
      ,'</GROUPNAME>',''),3,2000) as UserGroups  
FROM User_Groups LEFT JOIN Groups ON 
User_Groups.Group_ID=Groups.Group_ID
ORDER BY User_ID ASC

我想在MySQL中获得类似的最终结果(尝试过GROUP_CONCAT等)但是不成功..我怎样才能在MySQL中得到类似的**结果。请注意表格已经存在,我无法更改它们。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这有效:

SELECT
    t1.User_ID AS UserID,
    (
        SELECT
            GROUP_CONCAT(t2.GroupName)
        FROM
            Groups t2
        WHERE
            t2.Group_ID IN(
                    SELECT
                        t3.Group_ID
                    FROM
                        User_Groups t3
                    WHERE
                        t3.iUser_ID = t1.User_ID
            )
    ) AS GroupNames
FROM
    Users t1

这看起来更好主意,因为你不想拥有用户名,所以不需要涉及Users表:

SELECT
    User_ID,
    GROUP_CONCAT(GroupName) AS GroupNames
FROM
    (
        SELECT
            t2.User_ID AS User_ID,
            t3.GroupName AS GroupName
        FROM
            User_Groups t2
        LEFT JOIN
            Groups t3 ON (t3.Group_ID = t2.Group_ID)
    ) tmp
GROUP BY
    User_ID