让我们说我们有三张桌子Baseball_players,Bats,Plays_with_bat
Baseball_players
player_id | name
----------+-------
1. 01 | Jackson
2. 02 | Smith
3. 03 | Washington
3. 04 | Stein
和
Plays_with_bat
player_id | Bat_id
----------+-------
1. 01 | 01
2. 01 | 02
3. 02 | 01
4. 03 | 01
5. 04 | 01
6. 04 | 02
和
蝙蝠
Bat_id | Manufacturer
-------+-------
1. 01 | Easton
2. 02 | Rawlings
我想知道的是如何让所有使用Bats
次的玩家退回一次。 Bat_id
是Plays_with_bat
表中的外键,player_id
是Plays_with_bat
表中的外来词。
所以我想要的输出就像
player_id
----------
01
04
只有已经使用过所有球棒的球员
答案 0 :(得分:1)
你应该能够使用这样的东西:
select bp.player_id
from Baseball_players bp
inner join Plays_with_bat p
on bp.player_id = p.player_id
group by bp.player_id
having count(distinct p.bat_id) = (select count(distinct bat_id)
from bats)
结果:
| PLAYER_ID |
-------------
| 1 |
| 4 |
答案 1 :(得分:1)
您可以使用一个非常简单的查询来比较计数:
select player_id from Baseball_players p
where (select count(*) from Plays_with_bat pb where pb.player_id=p.player_id)
=
(select count(*) from Bats)
它说的是Plays_with_bat
中给定玩家的记录数必须等于Bats
中的记录总数。
答案 2 :(得分:0)
试试这个:
SELECT player_id
FROM Baseball_players p
WHERE player_id IN
(
SELECT player_id
FROM
(
SELECT player_id, COUNT(bat_id)
FROM Plays_with_bat
GROUP BY player_id
HAVING COUNT(DISTINCT bat_id) = (SELECT COUNT(bat_id) FROM bats)
) t
)