mysql - 如何在多个表上执行完全外连接
问题描述
我是 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
你能告诉我我做错了什么吗......?
解决方案
你不想要一个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
推荐阅读
- c# - Window 操作系统上的 GridDB,C# 客户端
- android - 删除表中的最后一行时,Android Room Flow 不会发出
- java - 尝试将二叉搜索树转换为数组(返回 Null)
- node.js - 如何在公牛,快递中获得工人完成处理的通知
- c# - 为什么我在运行 ASP.net MVC webapplication 3.1 时会出现此错误
- prolog - 获取 2 个唯一的子列表,它们都包含 2D 列表中的变量
- java - javafx中的连接客户端问题,聊天应用程序
- r - 如何在闪亮的r中将ggplot放在renderPlot中?
- c# - C#双重事实来源(字典和值项)
- mysql - 按生日排序