MySQL高级查询( 四 )

 
执行sql文件给areas表导入数据:
 

source areas.sql;
 
sql文件内容:
 
insert into areas values('11000', '北京市', null); insert into areas values('11001', '北京市', '11000'); insert into areas values('11002', '东城区', '11001'); insert into areas values('11003', '西城区', '11001'); insert into areas values('11004', '朝阳区', '11001'); insert into areas values('11005', '丰台区', '11001'); insert into areas values('11006', '海淀区', '11001'); insert into areas values('12000', '河北省', null); insert into areas values('12001', '石家庄市', '12000'); insert into areas values('12002', '长安区', '12001'); insert into areas values('12003', '桥东区', '12001'); insert into areas values('12004', '桥西区', '12001'); insert into areas values('12005', '新华区', '12001');
 
说明:
 
  • source 表示执行的sql文件
 
自连接查询的用法:
 
select c.id, c.title, c.pid, p.title from areas c inner join areas p on c.pid = p.id;
 
说明:
 
  • 自连接查询必须对表起别名
 
MySQL高级查询

文章插图
 
六、子查询
在一个select语句中,嵌入了另外一个select语句,那么被嵌入的select语句称之为子查询语句,外部的那个select语句则称为主查询
主查询和子查询的关系:
 
  1. 子查询是嵌入到主查询中
  2. 子查询是辅助主查询的,要么充当条件,要么充当数据源
  3. 子查询是可以独立存在的语句,是一条完整的select语句
 
查询大于平均年龄的学生:
 
select * from students where age > (select avg(age) from students);
 
MySQL高级查询

文章插图
 
查询学生在班的所有班级名字:
 
select name from classes where id in (select c_id from students where c_id is not null);
【MySQL高级查询】 
MySQL高级查询

文章插图
 
查找年龄最大,身高最高的学生:
 
select * from students where age=(select max(age) from students) and height=(select max(height) from students); 可以简写为: select * from students where (age,height) = (select max(age), max(height) from students);
 
MySQL高级查询

文章插图




推荐阅读