如果需要取的表中的字段信息为必须不为空字段,则用inner join;如果可为空,或者可有可没有,则用left join;right join 用法和left join 类似,不常用;union 合并去重;union all 合并不去重
语法:
*select * from 表A innner join 表B on 条件*
取的是A表和B表的交集,*所取数据均有值,为空则舍去*
select * from 表A left join 表B on 条件
以A表为准,取A表的全部数据,联接B表的数据
select * from 表A right join 表B on 条件
以B表为准,取B表的全部数据,联接A表的数据
举个栗子
表A
CREATE TABLE stu(
id int,
name varchar(10));
INSERT INTO stu VALUES (1,'a'),(2,'b'),(3,'c') ;
表B
CREATE TABLE score(
name varchar(10),
score int);
INSERT INTO score VALUES ('b',90),('c',85),('d',100);
SELECT * FROM stu A
inner JOIN score b ON a.name=b.name
id | name | name | score |
---|
2 | b | b | 90 |
3 | c | c | 85 |
SELECT * FROM stu A
LEFT JOIN score b ON a.name=b.name
id | name | name | score |
---|
1 | a | null | null |
2 | b | b | 90 |
3 | c | c | 85 |
left join 常用于过滤,取A表有但B表没有的,常在后面加上
WHERE b.name IS null 使用,输出结果如下
id | name | name | score |
---|
1 | a | null | null |
id | name | name | score |
---|
2 | b | b | 90 |
3 | c | c | 85 |
null | null | d | 100 |
id | name | name | score |
---|
1 | a | null | null |
2 | b | b | 90 |
3 | c | c | 85 |
null | null | d | 100 |