按MySQL中子表中的数据过滤父表

时间:2018-03-13 17:24:11

标签: mysql

有2个表可以跟踪棒球运动员及其位置..

播放器

+----+----------
| id | name    
+----+----------
|  1 | Boggs    
|  2 | Mattingly
|  3 | Judge
|  4 | Martinez
|  5 | Rodriguez

位置

+----+----------+-----------+
| id | player_id |   position   
+----+----------+-----------+
|  1 | 1        | Pitcher   
|  2 | 1        | Third Base    
|  3 | 2        | First Base  
|  4 | 3        | Second Base    
|  5 | 3        | Pitcher     

所以博格斯是一名投手并且打三垒,而马丁利只打第一页,而法官则是一名精灵和二垒手。

在MySQL中是否有办法只获得不是投手的玩家?所以这个样本的结果应该只是Mattingly。

当然我做不到......

select id from Player where id not in (select player_id from Position where position = 'Pitcher')

因为这会让Mattingly,Boggs和Judge回归。

3 个答案:

答案 0 :(得分:2)

select p.* from player p
join position pn on p.id = pn.player_id
where pn.position not in ('Pitcher')

答案 1 :(得分:1)

你试过了吗?

select id from Player where id not in 
    (select player_id from Position WHERE position = 'Pitcher')

答案 2 :(得分:1)

您需要将表格的名称从'Position'更改为'Positions',因为它的名称不应与您的列名相同。一旦完成,您应该能够在上面的答案中使用查询。

select id from Player where id not in 
(select player_id from Position WHERE position = 'Pitcher')