SQL 语法基础重温

SQL的相关语法记录

【连接】

相关内容参考:

image-20240201102222750

INNER JOIN 内连接

image-20240201102758142

通过两个集合的交集部分进行其它数据列的连接:

SELECT *
# 只拿出已经有成绩id的科目id来相连接
FROM subject JOIN score ON subject.id = score.id

这种连接方式和以下的代码达到的效果类似:

SELECT *
FROM subject, score
WHERE subject.id = score.id
LEFT JOIN 左连接

image-20240201103355377

通过左表目标id进行两表的连接

SELECT *
# 因为右表id中不一定会有左表id的对应顺序,因此可能存在null(非交集部分)
FROM subject LEFT JOIN score ON subject.id = score.id

那么这些左表空部分(LEFT JOIN EXCLUDING INNER JOIN),便是:

SELECT *
FROM subject LEFT JOIN score ON subject.id = score.id
WHERE score.id IS null
RIGHT JOIN 右连接

image-20240201104039461

和左连接类似,连接的左边为空部分及两表交集:

SELECT *
FROM subject RIGHT JOIN score ON subject.id = score.id

右表空部分(RIGHT JOIN EXCLUDING INNER JOIN):

SELECT *
FROM subject RIGHT JOIN score ON subject.id = score.id
# 注意,因为是以右表为主,因此左表为null的部分才是无交集部分
WHERE subject.id IS null
FULL OUTER JOIN 全外连接

image-20240201105134978

此种连接需注意:MySQL中不支持 FULL OUTER JOIN,但是SQL Server允许

SELECT *
FROM subject FULL OUTER JOIN score ON subject.id = score.id

当然,如上述用法,除去中心交集的连接也是存在的

SELECT *
FROM subject FULL OUTER JOIN score ON subject.id = score.id
WHERE subject.id IS null OR score.id IS null

···待续···

posted @ 2024-02-01 11:13  L`Lawliet  阅读(185)  评论(0编辑  收藏  举报