sql note 链接查询
1.链接查询
1.内连接
2.左链接
3.右链接
4.自链接
2.内连接查询
select 字段 from 表1 inner join 表2 on 表1.字段1 = 表2.字段2
e.g.select s.name, c.name from eleves as s inner join classes as c on s.c_id = c.id;
3.左连接
以左表为主根据条件查询右表数据,如果根据条件查询右表数据不存在使用null值填充
select 字段 from 表1 left join 表2 on 表1.字段1 = 表2.字段2;
e.g. select * from students s left join classes c on s.c_id = c.id;
4.右连接
select 字段 from 表1 right join 表2 on 表1.字段1 = 表2.字段2;
5.自连接
左表右表时同一个表,根据查询条件查询两个表的数据;
#执行sql 文件 source
select c.id, c.title, c.pid, p.title from areas as c inner join areas as p on c.pid = p.id where title=‘sfass’;
6.子查询
在一个select 语句中,嵌入了另外一个select语句称为子查询语句,外部的select语句称为主查询。
1.子查询的使用
select * from students where age > (select avg(age) from students);
select name from classes where id in (select cls_id from students where cls_id is not null);
select * from students where (age, height) = (select max(age), max(height) from studens);