如何查询(sql)不属于的运动员的运动项目?
How to query (sql) by listing the sports of the player doesn't belong to?
运动table
id
sport name
1
basketball
2
volleyball
3
golf
4
baseball
玩家table
id
sport name
1
michael
2
stephen
玩家运动table
id
player_id (players.id)
sport.id (sports.id)
1
1
1
1
1
4
2
2
1
2
2
3
我想要的结果:
迈克尔 (id: 1)
应该列出他不属于的运动:
- (2) 排球
- (3) 高尔夫
斯蒂芬 (id: 2)
应该列出他不属于的运动:
- (2) 排球
- (4) 棒球
这是我为 Michael 做的 sql,但它 return 来自 playersports table 的所有数据,包括 Stephen sports
SELECT * FROM `sports` LEFT JOIN `playersports` ON `sports`.id = `playersports`.sport_id WHERE `playersports`.`player_id` != 1;
您可以排除属于玩家 1
的所有 sort_ids
SELECT s.id,s.name
FROM sports s WHERE s.id NOT IN ( SELECT sport_id FROM player_sports WHERE player_id = 1)
运动table
id | sport name |
---|---|
1 | basketball |
2 | volleyball |
3 | golf |
4 | baseball |
玩家table
id | sport name |
---|---|
1 | michael |
2 | stephen |
玩家运动table
id | player_id (players.id) | sport.id (sports.id) |
---|---|---|
1 | 1 | 1 |
1 | 1 | 4 |
2 | 2 | 1 |
2 | 2 | 3 |
我想要的结果:
迈克尔 (id: 1) 应该列出他不属于的运动:
- (2) 排球
- (3) 高尔夫
斯蒂芬 (id: 2) 应该列出他不属于的运动:
- (2) 排球
- (4) 棒球
这是我为 Michael 做的 sql,但它 return 来自 playersports table 的所有数据,包括 Stephen sports
SELECT * FROM `sports` LEFT JOIN `playersports` ON `sports`.id = `playersports`.sport_id WHERE `playersports`.`player_id` != 1;
您可以排除属于玩家 1
的所有 sort_idsSELECT s.id,s.name
FROM sports s WHERE s.id NOT IN ( SELECT sport_id FROM player_sports WHERE player_id = 1)