[英]MySQL Select All Rows with Distinct Count Greater Than
我有一個表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
重復的行及其重復的次數,例如使用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
您的查詢是確定哪個關系重復的步驟。
要獲取所需的數據,您需要使用此結果並將其鏈接到同一表以對結果進行過濾。
這是查詢:
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
盡管AD的答案使用子查詢,但您也可以嘗試查看:
Create view relationship_view As Select relationshipID, userID, teamID, count( ) from relationship having count( ) > 1;
然后只需查詢該視圖即可: select * from relationship_view group by userID, teamID;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.