多表查询

多表查询

union(联合查询)

select name,age from people union (distinct) select id,name from score;
多表查询

inner join(联合查询)

select name,score from student inner join result on student.id=result.stuId;
多表查询
注:查询student表中的name与result表中的score,两表的公共字段为id,stuId。

left join(联合查询)

select name,score from student left join result on student.id=result.stuId;
多表查询

注:与inner join类似,区别在于查询时以左表(student)为基准。

right join(联合查询)

select name,score from student right join result on student.id=result.stuId;
多表查询

注:与left join 相反,区别在于查询时以右表(result)为基准。

cross join (联合交叉查询)

例1:select * from result cross join student;

返回表1(result)与表2(student)的笛卡尔积交叉结果。

例2:select * from result cross join student where student.id=result.stuId;

查询出公共字段(指定的)的所有数据。
多表查询

natural join(自然联合查询)

例1: select * from result natural join student;

查询出公共字段(字段名必须相同)的所有数据,若无同名的字段则返回笛卡尔积
多表查询

例2: select * from result natural right join student;

向右表看齐(以右表为基准)
多表查询
向左看齐同理。

using (指定公共字段)

select * from result inner join student using(id);

lect * from result inner join student using(id);

指定id为两表的公共字段,并返回查询的数据。(一般用于两表中有多个同名字段时)