我有一张表relationship
,如下所示:
relationshipId userId teamId
-------------- ------ ------
1 1234 999
2 5678 999
3 1234 888
4 1234 999
我想要做的是创建一个查询,向我显示userId,teamId组合在表格中重复的每一行。
我知道我可以使用像select userId, teamId, count(*) from relationship group by userId, teamId having count(*) > 1
这样的查询找到重复的行及其重复的次数
以上查询将返回:
userId teamId count
------ ------ -----
1234 999 2
我想要的是一个查询,它会向我显示产生count of 2
的两行,以便我可以访问唯一的relationshipIds
。
所以,我正在寻找结果:
relationshipId userId teamId
-------------- ------ ------
1 1234 999
4 1234 999
答案 0 :(得分:1)
您的查询是识别哪个关系重复的步骤。
要获取所需的数据,您需要使用此结果并将其链接到同一个表以过滤结果。
以下是查询:
select a.*
from relationship as a
, (
select userId
, teamId
from relationship
group by userId
, teamId
having count(*) > 1
) as b
where a.userId = b.userId
and a.teamId = b.teamId
答案 1 :(得分:0)
虽然A.D.的答案使用子查询,但您也可以尝试查看:
Create view relationship_view As
Select relationshipID, userID, teamID, count()
from relationship
having count() > 1;
然后只查询该视图:
select * from relationship_view
group by userID, teamID;