SQL查询组的结果

时间:2014-02-20 07:44:28

标签: mysql sql hibernate select group-by

我对所有的hibernate和SQL范围都很新,所以请原谅我这个愚蠢的问题。

我想使用hibernate进行sql查询,它将使用groupUserName对所有结果进行分组。

我的数据库中有以下表格:

ms_GroupUser:

+-------------+---------------+----------+---------+
| groupUserId | groupUserName | password | groupId |
+-------------+---------------+----------+---------+
|           1 | Alice         | 123456   |       1 |                
|           2 | BOB           | 654321   |       1 |
|           3 | BOB           | 654321   |       2 |
|           4 | Charlie       | 654321   |       1 |
+-------------+---------------+----------+---------+

ms_Group:

+---------+-----------+--------+----------------+------------+
| groupId | groupName | system | systemHostName | systemPort |
+---------+-----------+--------+----------------+------------+
|       1 | TEST      | FOO    | 1.1.1.1        |       8080 |
|       2 | TEST2     | FOO    | 1.1.1.1        |       8080 |
+---------+-----------+--------+----------------+------------+

我的查询是:

SELECT groupt.groupname, 
       usert.groupusername 
FROM   ms_group AS groupt, 
       ms_groupuser AS usert 
WHERE  groupt.groupid = usert.groupid 
       AND usert.password = '654321' 
GROUP  BY usert.groupusername 

我希望它会让我回到这个包里:

  

BOB - > TEST,TEST2。

     

查理 - > TEST。

实际带来的是:

  

BOB - > TEST。

     

查理 - > TEST。

TEST2在哪里?

你能帮帮我吗?我想念一些东西吗?

非常感谢!

3 个答案:

答案 0 :(得分:2)

SELECT groupUserName,groupName 
FROM ms_GroupUser u, ms_group g
WHERE g.groupId=u.groupId
AND u.password=654321 

<强>输出

| GROUPUSERNAME | GROUPNAME |
|---------------|-----------|
|           BOB |      TEST |
|           BOB |     TEST2 |
|       Charlie |      TEST |

<强> Fiddle

修改

根据您在评论中提出的问题

SELECT groupUserName,GROUP_CONCAT(groupName)
FROM ms_GroupUser u, ms_group g
WHERE g.groupId=u.groupId AND u.password=654321 
GROUP BY groupUserName

<强>输出

| GROUPUSERNAME | GROUP_CONCAT(GROUPNAME) |
|---------------|-------------------------|
|           BOB |              TEST,TEST2 |
|       Charlie |                    TEST |

<强> Fiddle

答案 1 :(得分:0)

只需在组中添加“group.group Name”即可。所以代码将变成这样的

SELECT groupt.groupName,
       usert.groupUserName
FROM   Group1 AS groupt,
       GroupUser AS usert
WHERE  groupt.groupId = usert.groupId
AND    usert.password = '654321'
GROUP  BY groupt.groupName,
       usert.groupUserName; 

答案 2 :(得分:0)

SELECT A.groupUserName,B.groupName
FROM ms_GroupUser A LEFT JOIN ms_Group B
ON A.groupID=B.groupID