1

假设我们有三张桌子 Baseball_players, Bats, Plays_with_bat

棒球运动员

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_idPlays_with_bat

所以我想要的输出就像

player_id  
----------
01
04  

只有已经使用过所有球棒的球员

4

3 回答 3

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)

请参阅带有演示的 SQL Fiddle

结果:

| PLAYER_ID |
-------------
|         1 |
|         4 |
于 2012-11-30T17:56:24.360 回答
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

sqlfiddle 上的演示

于 2012-11-30T18:04:18.370 回答
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
)

SQL 小提琴演示

于 2012-11-30T17:56:55.973 回答