python学习笔记 day43 子语句查询+关键字

1. 子语句查询

子语句其实就是sql语句的嵌套,外层的sql语句成为父语句,内层的sql语句成为子语句,第一次查询的结果可以作为第二次查询的条件或者表名来使用;

1.1 首先来看子语句查询结果作为表名:

select * from (select * from person) as aaa;   # 括号中的sql语句就是子语句,将该子语句的查询结果作为父语句的表名;

这里需要注意:将子语句的查询结果作为外层sql语句的表名时需要起一个别名;

运行结果:

1.2 子语句的查询结果作为外层语句的查询条件:

select * from person where dept_id=(select did from dept where name="研发部");   # 子语句的查询结果作为外层sql语句的查询条件(就是筛选研发部的员工信息)

运行结果:


1.3 查询最大工资的那个人的名字和薪水:

select name,salary from person where salary=(select max(salary) from person);  # 子语句查询到最大工资,外层sql语句安公子匹配名字;

运行结果:

1.4  查询工资高于所有人员平均工资的人员

select * from person where salary>(select avg(salary) from person);

运行结果:

 1.5 查询平均年龄在20岁以上的部门名:

方法一(使用子语句作为查询条件)

select dept.name from dept where did in (select dept_id from person group by dept_id having avg(age)>25) 

运行结果:

方法二: 使用联合查询:

select dept.name,avg(age) from person,dept where dept.did=person.dept_id group by dept_id having avg(age)>25;  # 使用联合查询,关联条件是person的dept_id=dept的did,查找部门平均年龄大于25的,用到了分组

运行结果:

方法三: 使用内连接查询(其实很联合查询的效果是一样的,只是语法不太一样,联合查询关联条件用where,多张表之间用逗号隔开,  连接查询关联条件使用on 中间关键字 inner join):

select dept.name,avg(age) from person inner join dept on dept.did=person.dept_id group by dept_id having avg(age)>25;  # 使用内链接查询,使用了分组查询,带有条件(每一组平均年龄需要判别)

运行结果:

1.6 查询研发部下的所有人员信息:

方法一: 使用子语句查询:

select * from person where person.dept_id =(select did from dept where dept.name="研发部"); # 子语句的查询结果作为外层语句的判断条件

运行结果:

方法二: 使用联合查询(多个表之间采用逗号隔开,关联字段的条件采用where):

select * from person,dept where dept.did=person.dept_id and dept.name="研发部"; #使用联合查询,多个表之间采用逗号隔开,关联字段的条件是where

运行结果:

方法三: 使用内连接查询(多个表之间采用inner join,表之间的关联字段条件使用on)

select * from person inner join dept on dept.did=person.dept_id where dept.name="研发部";

运行结果:

 1.7 查询大于所有人平均工资的人员姓名和年龄:

select name,age from person where salary>(select avg(salary) from person);

运行结果:

 

2. 关键字---any all some exists

2.1 any ----如果any内部查询语句返回结果有三个,比如result1,result2,result3,,,等那么

select ...from ...where a >any(...) ==》 select ...from ...where a>result1 or a>result2 or a>result3;  (中间使用or连接)

2.2 all----中间使用and连接多个结果:

select ...from ...where a >all(...) ==》 select ...from ...where a>result1 and a>result2 and a>result3;  (中间使用and 连接)

2.3 some ---作用同any (多个结果之间使用or连接)

2.4 exists ----子语句查询有结果,返回Ture会执行外层sql语句; 反之不会执行外层sql语句;(not exists 刚好与之相反)

select ... from....where exists(subquery----子语句)   可以理解为主查询(外部查询)会根据子查询的验证结果 True or False 来决定主查询是否得以执行;

如果子查询语句可以查到结果,就会返回True 主查询就会执行,反之 主查询不会执行;

select * from person where exists (select * from person where id>14) # 子查询语句查询不到结果(因为person表只有13条数据),所以子查询返回False 主查询不会执行

运行结果:

如果not exists:

select * from person where not exists (select * from person where id>14) # 子查询语句查询不到结果(因为person表只有13条数据),所以子查询返回False 主查询不会执行

运行结果:

talk is cheap,show me the code
原文地址:https://www.cnblogs.com/xuanxuanlove/p/9873699.html