依靠Group_Concat

时间:2016-04-06 21:58:11

标签: c# mysql sql

我在我的查询中应用了Group_Concat,结果显示得很好。以下是我的查询,

SELECT tblUserGroup.GroupID, GROUP_CONCAT(tblUserGroup.UserId) AS UserIds FROM     
tblGroup 
INNER JOIN tblUserGroup ON tblGroup.GroupID = tblUserGroup.GroupID 
GROUP BY tblUserGroup.GroupID
ORDER BY (UserIds)

现在输出就是这样的。

GroupID     UserIds
   1           1,2
   2           1,4
   3           1,2,3
   4           1,2
   5           1,2
   6           1,2,3

我已经在GROUP_CONCAT和COUNT上阅读了不同的问题,但是我想在不使用UserId的情况下应用count,而是想在theGROUP_CONCAT上应用count,例如" 1,2"。

我想要的是修改此查询,使其仅显示多次出现的记录。例如1,2和1,2,3

2 个答案:

答案 0 :(得分:1)

您是否尝试过使用子查询?它会是这样的:

SELECT Sub.UserIds, COUNT(*) as Qt
FROM (
    SELECT tblUserGroup.GroupID, GROUP_CONCAT(CONVERT(tblUserGroup.UserId, CHAR(20)) SEPARATOR ',') AS UserIds, count(*) FROM     
    tblGroup 
    INNER JOIN tblUserGroup ON tblGroup.GroupID = tblUserGroup.GroupID 
    GROUP BY tblUserGroup.GroupID HAVING COUNT(*) > 0
) AS Sub
GROUP BY Sub.UserIds

答案 1 :(得分:0)

也许你可以使用count并使用下面的查询(我无法测试它):

SELECT tblUserGroup.GroupID, GROUP_CONCAT(tblUserGroup.UserId) AS UserIds, count(*) FROM     
tblGroup 
INNER JOIN tblUserGroup ON tblGroup.GroupID = tblUserGroup.GroupID 
GROUP BY tblUserGroup.GroupID HAVING COUNT(*) > 0
ORDER BY (UserIds)