sql中的左连接和右连接

两张表,A表中的记录B表中不一定有。

左连接:关注左边,右边没有就为空。
右连接:关注右边,左边没有就为空。
内连接:返回交集
例如:
student表s

id name age class_id
1 yang 22 1
2 su 20 1
3 fan 20 2
4 li 30 2
5 luo 22

class表c

id name total
1 大一 30
2 大二 15
3 大三 40

在上面的表中,s表中的5号记录在c表中是找不到数据的。
1.左连接,left join左边为主要表,次表没有对应的就显示NULL。

SELECT s.`name`,s.`class_id` FROM student s LEFT JOIN class c ON s.`class_id`=c.`class_id`

结果

name class_id
yang 1
su 1
fan 2
li 2
luo (NULL)

2.右连接,right jion右边为主要表,次表没有对应的就显示NULL。

SELECT s.`name`,s.`class_id` FROM student s RIGHT JOIN class c ON s.`class_id`=c.`class_id`

结果

name class_id
yang 1
su 1
fan 2
li 2
(NULL) (NULL)

猜你喜欢

转载自www.cnblogs.com/yang37/p/12936146.html