执行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;
说明:
- 自连接查询必须对表起别名
文章插图
六、子查询
在一个select语句中,嵌入了另外一个select语句,那么被嵌入的select语句称之为子查询语句,外部的那个select语句则称为主查询
主查询和子查询的关系:
- 子查询是嵌入到主查询中
- 子查询是辅助主查询的,要么充当条件,要么充当数据源
- 子查询是可以独立存在的语句,是一条完整的select语句
查询大于平均年龄的学生:
select * from students where age > (select avg(age) from students);
文章插图
查询学生在班的所有班级名字:
select name from classes where id in (select c_id from students where c_id is not null);【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中的锁机制
- M MySQL VARCHAR最多能存储多少数据
- 站长如何通过内部链接获取流量,流量增长能带动收录查询吗
- 金木水火土五行查询表大全 金木水火土命
- 李易峰|李易峰再一次把王思聪推上神坛,大家都感慨还是王校长高级
- 唐嫣|唐嫣婚后更甜美了!穿香槟色抹胸裙高级又端庄,当了妈身材依旧辣
- 高考免费数据库查询 高考数据库
- 刘亦菲|刘亦菲不愧是娱乐圈的一股清流!穿金色长裙高级又优雅,气质好仙!
- 车晓|车晓厉害之处是气质把握得很棒,排骨胸看似瘦过头,穿衣却很高级