我正在寻找一个SQL查询,它选择x行,其中列最终只有唯一值。
表名为keezdrives_played 列被称为:team_id和opponents_id
[数据库图片。] [1]
这应该是这样的: [实施例] [2]
team_id和opponents_id具有唯一值
答案 0 :(得分:0)
您可以使用以下查询执行此操作:
SELECT t.team_id ,o.opponents_id FROM yourTAble t
INNER JOIN (
SELECT team_id,opponents_id FROM yourTAble
GROUP BY opponents_id
HAVING count(*) = 1
) AS o ON o.team_id = t.team_id
GROUP BY t.team_id
HAVING count(*) = 1;
<强>样品强>
mysql> select * from yourTable;
+---------+--------------+
| team_id | opponents_id |
+---------+--------------+
| 1 | 5 |
| 1 | 6 |
| 2 | 7 |
| 2 | 80 |
| 3 | 9 |
| 4 | 11 |
| 4 | 22 |
| 8 | 5 |
+---------+--------------+
8 rows in set (0,00 sec)
mysql> SELECT t.team_id ,o.opponents_id FROM yourTAble t
-> INNER JOIN (
-> SELECT team_id,opponents_id FROM yourTAble
-> GROUP BY opponents_id
-> HAVING count(*) = 1
-> ) AS o ON o.team_id = t.team_id
-> GROUP BY t.team_id
-> HAVING count(*) = 1;
+---------+--------------+
| team_id | opponents_id |
+---------+--------------+
| 3 | 9 |
+---------+--------------+
1 row in set (0,00 sec)
mysql>
查看评论
mysql> SELECT count(*) AS cnt , team_id
-> FROM keezdrives_played
-> GROUP BY team_id
-> ;
+-----+---------+
| cnt | team_id |
+-----+---------+
| 4 | 2281 |
| 4 | 2282 |
| 4 | 2283 |
| 4 | 2284 |
| 4 | 2285 |
| 4 | 2286 |
+-----+---------+
6 rows in set (0,00 sec)
mysql>
再试一次
SELECT team_id,opponents_id
FROM keezdrives_played
GROUP BY CONCAT(team_id, '-', opponents_id)
HAVING count(*) = 1;
上次尝试
SELECT * FROM (
SELECT t.team_id ,t.opponents_id
FROM keezdrives_played t
GROUP BY t.team_id
) r
GROUP BY r.opponents_id;
答案 1 :(得分:0)
我希望这就是你想要的
SELECT DISTINCT team_id ,opponents_id FROM keezdrives_played where drive_id=144;