SQL 语法基础重温

SQL的相关语法记录

【连接】

相关内容参考:

INNER JOIN 内连接

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

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

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

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

通过左表目标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 右连接

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

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 全外连接

此种连接需注意: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

···待续···

热门相关:新汉普夏饭店   医妓·荣华馆   盛宠之嫡女医妃   虎狼之师   花开春暖