# 分组中的查询字段中只能出现分组列或聚合函数select 列名,聚合函数 from 表名 groupby 列名
# 对分组后的结果再进行条件过滤select 列名 from 表名 groupby 列名 having 条件
5、子查询
概述:SELECT 语句出现在其他语句中
类型
单行单列:返回的是一个具体列的内容,可以理解为一个单值数据
单行多列:返回一行数据中多个列的内容
多行单列:返回多行记录中同一列的内容,相当于给出一个操作范围
多行多列:查询返回的结果是一张临时表
# 单行单列的情况select*from 表名1where 列名1[=、!=、>、<](返回单行单列的查询)# 单行多列的情况 select*from 表名 where(列名1,列名2)=(select 列名1,列名2from 表名 where条件);# 多行单列的情况,可以使用in、not in、any、allselect*from 表名1where 列名1in(返回多行单列的查询)# 多行多列的情况select*from 表名1leftjoin(返回多行多列的查询) 表别名 on 去除笛卡尔积条件
######################################################### 示例 ##### 单行子查询# 谁的工资比 Abel 高select last_name from employees where salary >(select salary from employees where name ='Abel');# 返回job_id 与141 号员工相同,salary 比143 号员工多的员工, 姓名,job_id(单行子查询) select name,job_id,salary from employees
where job_id =(select job_id from employees where employee_id =141)and
salary >(select salary from employees where employee_id =143);# 返回公司工资最少的员工的last_name,job_id 和salary(在子查询中使用组函数)select name,job_id,salary from employees
where salary <=(selectmin(salary)from employees)# 查询最低工资大于50 号部门最低工资的部门id(子查询中的having子句)select department_id,min(salary)from employees groupby department_id
havingmin(salary)>(selectmin(salary)from employees where department_id =50);######################################################## 多行子查询# 返回location_id 是1400 或1700的部门中的所有员工姓名(in操作符)select name from employees where department_id in(select department_id from departments
where location_id in(1400,1700));# 返回其它部门中比job_id 为‘IT_PROG’ 部门 任一 工资低的员工的员工号、姓名、job_id 以及salary(any)select employee_id,name,job_id,salary from employees where salary <any(select salary from employees where job_id ='IT_PROG')and job_id !='IT_PROG';# 返回其它部门中比job_id 为‘IT_PROG’ 部门 所有 工资低的员工的员工号、姓名、job_id 以及salary(all)select employee_id,name,job_id,salary from employees where salary <all(select salary from employees where job_id ='IT_PROG')and job_id !='IT_PROG';
6、多表关联查询
# 全值查询select*from 表1,表2where 去除笛卡尔积条件
# 内连接select*from 表1innerjoin 表2on 去除笛卡尔积条件
# 左外连接select*from 表1leftjoin 表2on 去除笛卡尔积条件
# 右外连接select*from 表1rightjoin 表2on 去除笛卡尔积条件
######################################################### 示例 #### 查询女神及其男朋友信息(等值连接)select b.id,b.`name`,bs.boyName from beauty b,boys bs where b.boyfriend_id = bs.id;# 查询女神及其男朋友信息(内连接)select b.id,b.name,bs.boyName from beauty b innerjoin boys bs on b.boyfriend_id = bs.id;# 查询女神及其男朋友信息(左外连接)select b.id,b.name,bs.boyName from beauty b leftjoin boys bs on b.boyfriend_id = bs.id;