首页 > 解决方案 > 如何在多个表上执行完全外连接

问题描述

我是 MySQL 新手,正在尝试对 3 个表执行完整的外部联接操作:

学生:-

usn(主键)

姓名

播放:-

usn(外键)

sport_id(外键)

运动 :-

sport_id(主键)

运动名称

我想得到参加一些运动的学生的名字,如果他们不参加任何运动,我想要 NULL(因此是完整的外部连接),

我尝试执行查询:

select student.name, sport.name 
from student 
full outer join plays on student.usn = plays.usn
full outer join sport on plays.sport_id = sport.sport_id;

但是,我收到一个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL 
server version for the right syntax to use near 'outer join plays on student.usn = plays.usn 
LIMIT 0, 25' at line 3

你能告诉我我做错了什么吗......?

标签: mysqlsqlfull-outer-join

解决方案


你不想要一个FULL JOIN. 你想要一个LEFT JOIN

select s.name, sp.name 
from student s left outer join
     plays p
     on s.usn = p.usn left outer join
     sport sp
     on p.sport_id = sp.sport_id;

Aleft join保留第一个表中的所有行和后续表中的匹配行——这正是您想要的。

FULL JOIN很少需要。我写了很多 SQL,几个月过去了,我没有full join在任何数据库中使用。

在此示例中,如果您想要所有没有学生的运动,FULL JOIN将使用a。也就是说,值可以出现在任何列中。NULL


推荐阅读