我无法为这种情况提出有效的查询...
表格
[ matchID ] [ User ] [ team ]
1 10 1
1 77 2
2 10 1
2 77 1
3 10 2
4 10 1
备注:
所需的查询结果:
对手未知的给定用户的matchID列表。
我的第一次尝试是:
SELECT matchID FROM table
GROUP BY matchID
HAVING COUNT(matchID) = 1
然后我意识到我没有计算队友但是未知对手的比赛,例如上面的比赛2。
用简单的英语,我需要把所有匹配ID都放在:
但我不确定如何在一个查询中有效地做到这一点。帮助
答案 0 :(得分:2)
SELECT MatchID
FROM Table
GROUP BY MatchID
HAVING COUNT(DISTINCT Team) = 1;
您似乎需要在表中只记录一个团队的匹配项,此查询会为您提供这些匹配项。
如果匹配必须涉及特定用户(样本数据为10),则:
SELECT t1.MatchID
FROM Table AS t1
WHERE EXISTS(SELECT *
FROM Table AS t2
WHERE t2.UserID = 10 AND t1.MatchID = t2.MatchID)
GROUP BY t1.MatchID
HAVING COUNT(DISTINCT t1.Team) = 1;
你可以这样做(内部)自我加入:
SELECT t1.MatchID
FROM Table AS t1
JOIN Table AS t2 ON t1.MatchID = t2.MatchID AND t2.UserID = 10
GROUP BY t1.MatchID
HAVING COUNT(DISTINCT t1.Team) = 1;
或者,或许更清楚一点:
SELECT t1.MatchID
FROM Table AS t1
JOIN (SELECT MatchID FROM Table AS t2 WHERE t2.UserID = 10) AS t2
ON t1.MatchID = t2.MatchID
GROUP BY t1.MatchID
HAVING COUNT(DISTINCT t1.Team) = 1;
子选择选择UserID 10播放的那些匹配;其余的工作和以前一样。
答案 1 :(得分:1)
您可以计算每场比赛的球队数量。如果只有一个,那就还不够:
SELECT matchID
FROM table
GROUP BY matchID
HAVING COUNT(DISTINCT(team))=1;
答案 2 :(得分:0)
您还没有提供表名,所以我决定将其称为mut
,简称为匹配用户团队。无论如何,这似乎适用于所有情况:
SELECT DISTINCT
`matchID`
FROM
`mut`
WHERE
`user`=10
AND
`matchID` NOT IN (
SELECT
`m1`.`matchID`
FROM
`mut` AS `m1`
INNER JOIN
`mut` AS `m2`
ON
`m1`.`matchID`=`m2`.`matchID`
AND
`m1`.`team`<>`m2`.`team`
)