您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

MySQL精讲之一:DQL数据查询语句

2024/3/10 5:39:57发布45次查看
免费学习推荐:mysql视频教程
目录
一、基础查询二、条件查询三、排序查询四、常见函数五、分组查询六、连接查询七、子查询八、分页查询九、联合查询样本数据准备
进行dql查询语句实验前,首先准备对应的数据,作为样本以供查询使用
使用sqlyog中导入该sql脚本,可以看到准备好的样本表:
该样本是某跨国企业员工管理的4张表,下图对每张表的各个字段做了介绍:
一、基础查询
语法:select 查询列表 from 表名;
特点:
查询列表可以是:表中的字段、常量值、表达式、函数。
查询的结果是一个虚拟的表格。
执行顺序:from > select (先找到表,再开始查询)
注意:`是着重号,当某张表中的字段与关键字冲突时,可以在该字段两边加上着重号,以标明其是一个字段,而不是关键字(如`name`)。
【基础查询】# 选中样本库user myemployees;# 1.查询表中的单个字段select last_name from employees;# 2.查询表中的多个字段select last_name,salary,email from employees;# 3.查询表中所有的字段select * from employees;# 4. 查询常量值select 'tom';# 5.查询表达式select 7%6;# 6. 查询函数select version();# 7.起别名(mysql中建议将起别名使用双引号引起来别名)/*优点:便于理解;连接查询时,如果要查询的字段有重名情况,可以使用起别名来区分*/# 方式一,使用asselect 7%6 as 结果;select last_name as 姓,first_name as 名 from employees;# 方式二,使用空格select 7%6 结果;select last_name 姓,first_name 名 from employees;# 查询员工号为176的员工的姓名、部门、nianxinselect last_name,department_id,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees; # 8.去重select distinct department_id from employees;# 9.+号的作用/*select 13+21; 两个操作数都是数值型,自动做加法运算其中一个为字符型,则将字符型转换为数值型 select '13'+1;     转换成功,做加法运算 select 'hello'+1;  转换失败,将字符型转换为0select null+10; 只要其中一方为null,结果就为null 补充ifnull函数:select ifnull(commission_pct,0) as 奖金率,commission_pct from employees;mysql中用来拼接的不是+号,而是concat函数*/select concat(last_name,first_name) as 姓名 from employees;
基础查询总结说明
1.查询表中的单个字段 select 字段1 from 表;
2.查询表中的多个字段 select 字段1,字段2,...字段n from 表;
3.查询表中的所有字段 select * from 表;
4.查询常量值 select '常量值;'
5.查询表达式 select 数值1 表达式 数值2;
6.查询函数 select f();
7.起别名 as
8.去重 distinct
9.拼接使用concat函数,而不是+ concat(last_name,first_name)
学完了基础查询,尝试完成下面的练习题
答案:
1.正确
2.正确
3.应在英文状态下使用引号
4.desc departments;;select * from departments;
5.select concat(first_name,',',last_name,',',ifnull(email,0)) as out_put from employees;
二、条件查询
语法:select 查询列表 from 表名 where 筛选条件;
执行顺序:from > where > select (先定位到表,然后开始筛选,最后走查询)
分类:
(1)按条件运算符筛选
条件运算符有: >  < = >=   <= !=(或<>)
(2)按逻辑表达式筛选
支持&& || !,但推荐使用and or not 逻辑表达式作用:用于连接条件表达式&&或and: 两个都为true,结果为true,反之为false||或or : 只要有一个条件为true,结果即为true,反之为false!或not : 取反
(3)模糊查询
模糊查关键字:like、between and、in、is null(1)like关键字 可以判断字符型或数值型   like一般和通配符搭配使用,通配符有 %:代表任意多个字符,包含0个 _:代表任意单个字符(2)between...and关键字   可以提高语句简洁度   包含临界值   两个临界值不能调换顺序(3)in关键字   可以提高语句简洁度   in列表的值类型必须一致(4)is null   取反是 is not null
【条件查询】(1)按条件运算符筛选# 1.查询工资>12000的员工select * from employees where salary > 12000 ;# 2.查询部门编号不等于90的员工名和部门编号select department_name, department_id from departments where department_id<>90;---------------------------------------------------------------------------------------------------------------------(2)按逻辑表达式筛选# 1.查询工资在10000到20000之间的员工名、工资以及奖金率select last_name,salary,commission_pct from employees where salary>=10000 and salary<=20000;# 2.查询部门编号不是在90到110之间的,或工资高于15000的员工信息select * from employees where not(department_id>=90 and department_id<=110) or salary>15000;---------------------------------------------------------------------------------------------------------------------(3)模糊查询# (1)like关键字# 1.查询员工名中包含字符a的员工的信息select * from employees where last_name like '%a%';# 2.查询员工名中第三个字符为n,第五个字符为l的员工名和工资select last_name,salary from employees where last_name like '__n_l%';# 3.查询员工名中第二个字符为_的员工名(转义)select last_name from employees where last_name like '_$_%' escape '$';# (2)between...and关键字# 1.查询员工编号在100到120的员工信息select * from employees where employee_id between 100 and 120;# (3)in关键字# 1.查询员工的工种编号是it_prog、ad_vp、ad_pres中的员工名和工种编号select last_name,job_id from employees where job_id in('it_prog','ad_vp','ad_pres');# (4)is null# 1.查询没有奖金的员工名和奖金率select last_name,commission_pct from employees where commission_pct is null;# is null仅仅可以用来判断null值;安全等于<=>既可以用来判断null值,又可以用来判断普通值# is null的可读性高于<=>,建议使用is nullselect last_name,commission_pct from employees where commission_pct <=> null;
条件查询总结说明
(1)按条件运算符筛选 > < = >= select > order by (order by一般放在查询语句的最后面,limit子句除外(后面会讲到))
【排序查询】# 1.查询员工信息,要求工资从高到低排序select * from employees order by salary desc;# 2.查询部门编号>=90的员工信息,按入职时间的先后进行排序【添加筛选条件】select * from employees where department_id>=90 order by hiredate asc;# 3.按照年薪的高低显示员工的信息和年薪【添加表达式排序】select * ,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees order by salary*12*(1+ifnull(commission_pct,0)) desc;select * ,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees order by 年薪 desc; # order by后支持别名# 4.按照姓名的长度,显示员工的姓名和工资【按函数排序】select length(last_name) as 字节长度, last_name,salary from employees order by 字节长度 desc;# 5.查询员工信息,先按工资升序,再按员工编号降序select * from employees order by salary asc ,employee_id desc;
学完了排序查询,尝试完成下面的练习题
答案:
1、select last_name,department_id,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees order by 年薪 desc,last_name asc;
2、select last_name,salary from employees where salary not between 8000 and 17000 order by salary desc;
3、select * from employees where email like '%e%' order by length(email) desc,department_id asc;
排序查询总结说明
升序 order by asc
降序 order by desc
四、常见函数
调用语法:select 函数名(实参列表) from 表;
概念:类似于java中的方法,将一组逻辑语句封装在方法体中,对外暴露接口。
好处:
1.隐藏了实现细节
2.提高代码重用性
分类:分为单行函数和分组函数。其中单行函数又分为:字符函数、数学函数、日期函数、系统函数、流程控制函数。;分组函数用来做统计功能,又称为统计函数、聚合函数、组函数。
单行函数说明
(1)字符函数 参数类型为字符型
获取参数值的字节个数 select length('字符串')
拼接 concat(字段1,字段2)
大小写转换 upper、lower
截取 substr(index,end)
查找 instr(主串,子串)
清除两边空格 trim(a from'aaaa字符串1aa')
左右填充 lpad('字符串1',左填充个数n,填充字符'a')、lpad('字符串1',右填充个数n,填充字符'a')
替换 replace('字符串1','被更换的字符串','新的字符串')
(2)数学函数 参数类型为数值
四舍五入 round(小数,保留位数)
截取 truncate(小数,保留位数)
向上取整 ceil(被向上取整的数值)
向下取整 floor(被向下取整的数值)
取余 mod(n,m);结果的正负和被取余数n相同
随机数 rand();返回0-1之间的小数
(3)日期函数 参数为日期
返回当前完整日期 select now();
返回当前年月日 select curdate();
返回当前时分秒 select curtime();
截取指定部分 select year(now()) as 年,month(now()) as 月,day(now()) as 日;
字符串→日期 str_to_date('2020-7-7','%y-%m-%d')
日期→字符串 date_format(now(),'%y年%m月%d日')
返回两个日期相差的天数 datediff(日期1,日期2)
(4)系统函数 系统自带
查看当前版本 select version();
查看当前数据库 select database();
查看当前用户 select user();
自动加密 password('字符');或md5('字符');
(5)流程控制函数 类比java
if if(奖金 is null,'没奖金','有奖金')
分组函数说明
sum 求和
avg 平均值
max 最大值
min 最小值
count 计算个数
【单行函数】# (1)字符函数-[参数类型为字符型]# 1.length 获取参数值的字节个数select length('john');select length('张三丰');show variables like '%char%' # 查看字符集# 2.concat拼接字符串select concat(last_name,'_',first_name) 姓名 from employees;# 3.upper、lower 大小写转换select upper('tom');select lower('tom')# 将姓变大写,名变小写,然后拼接select concat(upper(last_name),lower(first_name))姓名 from employees;# 4.substr 拼接函数# mysql中的索引从1开始select substr('若负平生意,何名作莫愁',7) as out_put;select substr('若负平生意,何名作莫愁',1,3) as out_put;# 案例:姓名中首字符大写,其他字符小写,用_拼接并显示出来select concat(upper(substr(last_name,1,1)),'_',lower(substr(last_name,2))) oup_put from employees; # 5.instr 字符查找函数# 返回子串在主串中的起始索引,没有返回零select instr('凡尘阿凉','阿凉') as out_put;# 6.trim 清除空格函数# 将字符两边的空格移除select length(trim('    凡尘    ')) as out_put;select trim('a' from  'aaaaaa凡aaa尘aaaa') as out_put;# 7.lpad 左填充函数# 用指定的字符实现左填充指定长度select lpad('凡尘',10,'*') as out_put;# 8.rpad 右填充函数# 用指定的字符实现右填充指定长度select rpad('凡尘',10,'*') as out_put;# 9.replace 替换函数select replace('我的偶像是鲁迅','鲁迅','周冬雨') as oup_put;---------------------------------------------------------------------------------------------------------# (2)数学函数-[参数类型为数值]# 1.round 四舍五入函数select round(1.65);select round(1.567,2);# 2.ceil 向上取整函数# 返回>=该参数的最小整数select ceil(1.00);# 3.floor 向下取整函数# 返回<=该参数的最大整数select floor(-9.99);# 4.truncate 截取函数 # 保留小数点后几位select truncate(1.65,1);# 5,mod 取余函数# 结果的正负和被除数相同:a-a/b*bselect mod(10,-3);---------------------------------------------------------------------------------------------------------# (3)日期函数-[参数为日期]# 1.now 返回当前完整日期select now();# 2.curdate 返回当前年月日select curdate();# 3.curtime 返回当前时分秒select curtime();# 4.获取指定的部分select year(now()) as 年;select year('1998-12-12') as 年;select year(hiredate) 年 from employees;select month(now()) 月 ;select monthname(now()) 月 ;# 5.str_to_date 将日期格式的字符转换为指定格式的日期select str_to_date('2020-7-7','%y-%m-%d') as out_put;# 查询入职日期为1992-4-3的员工信息select * from employees where hiredate = str_to_date('4-3 1992','%m-%d %y');# 6.date_format 将日期转换为字符select date_format(now(),'%y年%m月%d日');# 查询有奖金的员工和入职日期(xx月/xx日 xx年)select last_name,date_format(hiredate,'%m月/%d日 %y年') 入职日期 from employees where commission_pct is not null;---------------------------------------------------------------------------------------------------------# (4)系统函数# 1.查看当前版本select version()# 2.查看当前数据库select database();# 3.查看当前用户select user();---------------------------------------------------------------------------------------------------------# (5)流程控制函数# 1.if函数select if(10>5,'大于','小于');select last_name,commission_pct, if(commission_pct is null,'没奖金','有奖金') as out_put from employees;# 2.case函数/*方式一:类似于java中的switch-case:案例:查询员工工资,要求部门号=30,显示的工资为1.1倍部门号=40,显示的工资为1.2倍部门号=50,显示的工资为1.3倍其他部门,显示的工资为原工资*/select salary 原始工资,department_id,case department_idwhen 30 then salary*1.1when 40 then salary*1.2when 50 then salary*1.3else salaryend as 新工资from employees;/*方式二:类似于java中的多重if:案例:查询员工的工资情况工资>20000,显示a级别工资>15000,显示b级别工资>10000,显示c级别否则,显示d级别*/select salary,casewhen salary>20000 then 'a'when salary>15000 then 'b'when salary>10000 then 'c'else 'd'end as 工资级别from employees;
【分组函数】/*      sum 求和      avg 平均值      max 最大值      min 最小值      count 计算个数*/# 综合使用select sum(salary) 和,avg(salary) 平均数,max(salary) 最大值,min(salary) 最小值,count(salary) 总个数 from employees;/*分组函数的特点:   1.sum、avg一般用于处理数值型;max、min、count可以处理任何类型   2.分组函数都忽略null值,都可以和distinct搭配去重   3.和分组函数一同查询的字段要求是group by后的字段   4.count函数经常用来统计行数,使用count(*)或count(1)或count(常量)效率问题: myisam存储引擎下,count(*)效率高 innodb存储引擎下,count(*)和count(1)效率差不多,但比count(字段)要高*/
学完了单行函数,尝试完成下面的练习题
答案:
1、select now();
2、select employee_id,last_name,salary*1.2 new salary from employees;
3、select length(last_name) 长度,substr(last_name,1) 首字符,last_name from employees order by 首字符;
4、select concat(last_name,' earns '),salary,' monthly but wants ',salary*3 as dream salary from employees where salary=24000;
5、
select last_name,job_id as job,
case job_id
when ‘ad_pres’ then ‘a’
when ‘st_man’ then ‘b’
when ‘it_prog’ then ‘c’
when ‘sa_pre’ then ‘d’
when ‘st_clerk’ then ‘e’
end as “grade”
from employees
where job_id =“ad_pres”;
学完了分组函数,尝试完成下面的练习题:
答案:
1.select round(max(salary),2) 最大值,round(min(salary),2) 最小值,round(avg(salary),2) 平均值,round(sum(salary),2) 总和 from employees;
2.select datediff(max(hiredate),min(hiredate)) differnce from employees;
3.select count(*) as 员工个数 from employees where department_id=90;
五、分组查询
语法:
select 分组函数,查询列表(要求出现在group by的后面)
from 表
【where 筛选条件】
group by 分组的列表
【having 分组后的筛选】
【order by 子句】
执行顺序:from > where > group by > having > select > order by
分类筛选源位置关键字
分组前筛选 原始表 group by where
分组后筛选 分组后的结果集 group by having
注意:
1.查询列表必须是分组函数和group by后出现的字段。
2.分组函数做条件一定放在having子句中。
3.能用分组前筛选的优先使用分组前筛选。
4.group by子句支持单个字段分组、多个字段分组(多个字段之间用逗号隔开,没有顺序要求)、表达式或函数。
5.可以添加排序(排序放在整个分组查询最后)
6.一般不在group by和having后使用别名。
# 1.查询每个工种的最高工资select max(salary) 最高工资,job_id 工种 from employees group by job_id;# 2.查询每个位置上的部门个数select count(*) 部门个数,location_id 位置id from departments group by location_id;# 3.查询邮箱中包含a字符的,每个部门的平均工资select avg(salary) 平均工资,department_id 部门id from employees where email like '%a%' group by department_id;# 4.查询每个领导手下的有奖金的员工的最高工资select max(salary) 最高工资,manager_id 领导编号 from employees where not isnull(commission_pct)  group by manager_id;# 5.查询哪个部门的员工个数>2# 思路:查询每个部门的个数,再根据结果哪个部门的员工个数>2select count(*),department_id from employees group by department_id having count(*)>2;# 6.查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资select max(salary) 最高工资,job_id 工种 from employees where not isnull(commission_pct) group by job_id having max(salary)>12000;# 7.查询领导编号>102的每个领导手下员工的最低工资>5000的领导编号是哪个,以及其最低工资select min(salary) 最低工资,manager_id 领导编号 from employees where manager_id>102 group by manager_id having min(salary)>5000;# 8.按员工姓名的长度分组,查询每一组的员工个数,筛选员工个数>5的有哪些select count(*) 员工个数,length(last_name) 姓名长度 from employees group by length (last_name) having count(*)>5;# 9.查询每个部门每个工种的员工的平均工资select avg(salary) 平均工资,department_id 部门,job_id 工种 from employees group by department_id,job_id; # 10.查询每个部门每个工种的员工的平均工资,并按平均工资的高低显示select avg(salary) 平均工资,department_id 部门,job_id 工种 from employees group by department_id,job_id order by avg(salary) desc;
学完了分组查询,尝试完成下面的练习题
答案:
1、select max(salary),min(salary),avg(salary),sum(salary),job_id from employees group by job_id order by job_id asc;
2、select max(salary)-min(salary) difference from employees;
3、select min(salary) ,manager_id from employees where not isnull(manager_id) group by manager_id having min(salary)>=6000;
4、select department_id,count(*),avg(salary) from employees group by department_name order by avg(salary) desc;
5、select count(*) 个数,job_id from employees group by job_id;
六、连接查询
概念:查询的字段来自多个表。
分类:安装年代可以分为sql92和sq99,按照功能分为内连接(交集)、外连接(一个表中有,另一个表中没有)、交叉连接;其中sql92仅支持内连接,sql99除全外连接其他全都支持。
注意:
1.如果为表起了别名,则查询的字段就不能使用原来的表名去限定。
2.当涉及到多表查询时,为表起别名可以有效提高语句简洁度,方便区分多个重名的字段。
连接查询分为下面三类:
(1)内连接inner
等值连接非等值连接自连接(2)外连接
左外连接left outer右外连接right outer全外连接full outer(3)交叉连接cross
【sql92标准】# 1.等值连接# 查询女神名和对应的男朋友名# select name,boyname from boys,beauty where beauty.boyfriend_id=boys.id;# 1.查询员工名和对应的部门名select last_name 员工名,department_name 部门名 from employees,departments where employees.department_id=departments.department_id;# 2.查询员工名、工种号、工种名select last_name,e.job_id,job_title from employees e,jobs j where e.`job_id`=j.`job_id`;# 3.查询有奖金的员工名、部门名select last_name,department_name,commission_pct from employees e,departments d where e.`department_id`=d.`department_id` and e.`commission_pct` is not null;# 等值连接+筛选# 4.查询城市中第二个字符为o的部门名和城市名select department_name 部门名,city 城市名 from departments d,locations l where d.`location_id`=l.`location_id` and city like '_o%'; # 等值连接+分组# 5.查询每个城市的部门个数select count(*) 部门个数,city 城市 from departments d,locations l where d.`location_id`=l.`location_id` group by city;# 6.查询有奖金的每个部门的部门名、部门的领导编号、该部门最低工资select department_name,d.manager_id,min(salary) from departments d,employees e where d.`department_id`=e.`department_id` and commission_pct is not null group by department_name,d.manager_id;# 7.查询每个工种的工种名、员工的个数并按员工的个数降序select job_title,count(*) from employees e,jobs j where e.`job_id`=j.`job_id` goup by job_title order by count(*) desc;# 8.支持三表连接# 查询员工名、部门名、所在的城市select last_name,department_name,city from employees e,departments d,locations l where e.`department_id`=d.`department_id` and d.`location_id`=l.`location_id`;# (2)非等值连接/*先执行下面的语句,在myemployees数据库中创建新的job_grades表。create table job_grades(grade_level varchar(3), lowest_sal  int, highest_sal int);insert into job_gradesvalues ('a', 1000, 2999);insert into job_gradesvalues ('b', 3000, 5999);insert into job_gradesvalues('c', 6000, 9999);insert into job_gradesvalues('d', 10000, 14999);insert into job_gradesvalues('e', 15000, 24999);insert into job_gradesvalues('f', 25000, 40000);*/# 1.查询员工的工资和工资级别select salary,grade_level from employees e,job_grades j where salary between j.`lowest_sal` and j.`highest_sal`;# (3)自连接# 1.查询员工名和其上级的名称.select e.employee_id 员工id,e.last_name 员工姓名,m.employee_id 经理id,m.last_name 经理姓名 from employees e,employees m where e.`manager_id`=m.`employee_id`;
学完了sql92标准的连接查询,尝试完成下面的练习题
答案:
1、
select last_name,d.department_id,department_name
from employees e,departments d
where e.department_id=d.department_id;
2、
select e.job_id,d.location_id from employees e,departments d
where d.department_id=e.department_id
and e.department_id=90;
3、
select last_name , department_name , l.location_id , city
from employees e,departments d,locations l
where e.department_id=d.department_id and d.location_id=l.location_id and e.commission_pct is not null;
4、
select last_name , job_id , d.department_id , department_name
from employees e,departments d,locations l
where e.department_id=d.department_id and d.location_id=l.location_id and l.city=‘toronto’;
5、
select department_name,job_title,min(salary)
from departments d,employees e,jobs j
where d.department_id=e.department_id and e.job_id = j.job_id
group by job_title,department_name;
6、
select count(),country_id from departments d,locations l
where d.location_id=l.location_id
group by country_id
having count()>2;
7、
select e1.last_name “employees”,e1.employee_id “emp#”,e2.last_name “manager”,e2.employee_id “mgr#”
from employees e1,employees e2
where e1.manager_id=e2.employee_id and e1.last_name=‘kochhar’;
【sql99标准】# (1)等值连接# 1.查询员工名,部门名select last_name,department_name from employees einner join departments don e.department_id=d.department_id;# 2.查询名字中包含e的员工名和工种名(添加筛选)select last_name,job_titlefrom employees einner join jobs jon e.job_id=j.job_idwhere last_name like '%e%' or job_title like '%e%';# 3.查询部门个数>3的城市名和部门个数(分组+筛选)select city,count(*) 部门个数from departments dinner join locations lon d.location_id=l.location_idgroup by cityhaving count(*)>3;# 4.查询哪个部门的部门员工个数>3的部门名和员工个数,并按个数降序(排序)select department_name 部门名,count(*) 员工个数from departments dinner join employees eon d.department_id=e.department_idgroup by department_namehaving count(*)>3order by count(*) desc;# 5.查询员工名、部门名、工种名、并按部门名排序select last_name 员工名,department_name 部门名,job_title 工种名from employees einner join departments d on d.department_id=e.department_idinner join jobs j on e.job_id=j.job_idorder by department_name ;# (2)非等值连接# 查询员工工资级别select salary,grade_levelfrom employees ejoin job_grades j on e.`salary` between j.lowest_sal and j.highest_sal;# 查询每个工资级别的个数>20的个数,并且按照工资级别降序排列select count(*),grade_levelfrom employees ejoin job_grades j on e.`salary` between j.lowest_sal and j.highest_salgroup by grade_levelhaving count(*)>20order by grade_level desc;# (3)自连接# 查询员工的名字、上级的名字select e1.last_name 员工名,e2.last_name 上级名from employees e1join employees e2 on e1.manager_id=e2.employee_id;--------------------------------------------------------------------------------------------------------------# 二、外连接# 1.查询男朋友不在男神表的女神名# 左外连接select name from beauty left outer join boys on beauty.boyfriend_id=boys.idwhere boys.id is null;# 右外连接select namefrom boys right outer join beauty on beauty.boyfriend_id=boys.idwhere boys.id is null;# 2.查询没有员工的部门select d.department_name,e.employee_idfrom departments d left join employees e on d.department_id=e.department_idwhere e.manager_id is null;select * from employees where employee_id=100;# 3.全外连接(不支持)# 全外连接就是就并集use girls;select b.*,bo.*from beauty bfull join boys boon b.boyfriend_id=bo.id;# 三.交叉连接# 使用99标准实现的笛卡尔乘积,使用cross代替了92中的,select b.*,bo.*from beauty bcross join boys bo
学完了sql99标准的连接查询,尝试完成下面的练习题
答案:
一、
select b.name,bo.*
from beauty b left join boys bo
on b.boyfriend_id=bo.id
where b.id>3;
二、
select city “城市”,department_name “城市名”
from departments d right join locations l
on d.location_id=l.location_id
where d.department_id is null;
三、
select d.department_name,e.*
from departments d left join employees e
on d.department_id=e.department_id
where d.department_name in (‘sal’,‘it’);
七、子查询
含义:出现在其他语句中的select语句,称为子查询或内查询;外部的查询语句,称为主查询或外查询。
按子查询出现的位置分类:
select后面 (仅支持标量子查询)from后面 (支持表子查询)where或having后面 (支持标量、行、列子查询)☆☆☆exists后面 (又叫相关子查询,支持表子查询)按结果集的行列数分类:
标量子查询(结果集只有一行一列)列子查询(结果集只有一列多行)行子查询(结果集有一行多列)表子查询(结果集一般为多行多列)【where和having后的子查询】(支持标量、行、列子查询)# 1.单个标量子查询# 查询工资比abel工资高的员工名select last_name,salary from employees where salary>(select salary from employees where last_name='abel');# 2。多个标量子查询# 返回job_id与141号相同,salary比143号员工多的员工的姓名、job_id、工资。select last_name,job_id,salary from employeeswhere job_id=( select job_id from employees where employee_id=141)  and salary>(select salary from employees where employee_id=143);# 3。标量子查询+分组函数# 返回工资最少的员工的last_name、job_id和salaryselect last_name,job_id,salary from employees where salary=(select min(salary) from employees);# 4。标量子查询+having子句# 查询最低工资 >50号部门最低工资的 部门id和其最低工资select department_id,min(salary) from employees group by department_idhaving min(salary)>(select min(salary) from employees where department_id=50); # 5.列子查询(多行子查询)# 返回location_id是1400或1700的部门中的所有员工姓名.select last_name from employees where department_id in ( select distinct department_id from departments where location_id in(1400,1700));# 返回其它工种中比job_id为'it_prog'工种中任一工资低的员工的工号、姓名、job_id、以及salaryselect employee_id,last_name,job_id,salary from employeeswhere salarya.ag
4、思路:①查询姓名中包含字母u的员工的部门②查询部门号=①中任意一个的员工的工号和姓名
select employee_id “员工号”,last_name “姓名”
from employees
where department_id in(
select distinct department_id
from employees
where last_name like ‘%u%’
);
5、思路:①查询location_id=1700的部门②查询在①部门中工作的员工的员工号
select employee_id
from employees
where department_id in(
select distinct department_id
from departments
where location_id=1700
);
6、思路:①查询姓名为k_ing的员工编号②查询manager_id=①的姓名和工资
select last_name “员工姓名”,salary “工资”
from employees
where manager_id in(
select employee_id
from employees
where last_name=‘k_ing’
);
7、思路:①查询最高工资②查询工资=①的姓.名
select concat(first_name,last_name) “姓.名”
from employees
where salary=(select max(salary) from employees);
如果觉得做得不过瘾,可以继续挑战下面的子查询经典案例:
答案:
1、思路:①查询最低工资②查询工资=①的last_name, salary
select last_name, salary
from employees
where salary=(select min(salary) from employees)
2、思路一:①查询各部门的平均工资;②查询①结果上的最低平均工资③查询哪个部门的平均工资=②;④查询部门信息
select d.*
from departments d
where d.department_id=(
select department_id
from employees
group by department_id
having avg(salary)=(
select min(ag)
from (
select avg(salary) ag,department_id
from employees
group by department_id
) a
)
);
思路二:①使用排序求出最低平均工资的部门编号②查询部门信息
select * from departments
where department_id=(
select department_id
from employees
group by department_id
order by avg(salary) asc
limit 1
);
3、思路:①查询各部门平均工资;②查询最低平均工资的部门编号
select d.* ,ag
from departments d
join (
select avg(salary) ag,department_id
from employees
group by department_id
order by avg(salary) asc
limit 1
) a
on d.department_id=a.department_id;
4、思路:①查询job的平均工资最高的job_id;②查询job信息
select *
from jobs
where job_id=(
select job_id
from employees
group by job_id
order by avg(salary) desc
limit 1
);
5、思路:①查询公司平均工资;②查询每个部门的平均工资;最后筛选②中平均工资 > ①
select avg(salary),department_id
from employees
group by department_id
having avg(salary)>(
select avg(salary)
from employees
);
6、思路:①查询有manager的员工编号;②查询编号在①中的详细信息
select * from employees
where employee_id in (select distinct manager_id from employees);
7、思路:①查询各部门最高工资中最低的那个部门id;②查询①部门的最低工资啊
select min(salary) from employees where department_id=(
select department_id
from employees
group by department_id
order by max(salary) asc
limit 1
);
8、思路:①查询平均工资最高的部门编号;②将employees和departments连接查询,筛选条件是①
select last_name, d.department_id, email,salary
from employees e
inner join departments d on d.manager_id=e.employee_id
where d.department_id=(
select department_id
from employees
group by department_id
order by avg(salary) desc
limit 1
)
八、分页查询
应用场景:当要显示的数据一页显示不全,需要分页提交sql请求。
语法:
select 查询列表
from 表
[join type join 表2
on 连接条件
where 筛选条件
group by 分组字段
having 分组后的筛选
order by]
limit offset,size;
offset:从0开始的起始索引,若省略默认从第一条开始
size:要显示的条目个数
执行顺序:from > join > on > where > group by > having > select > order by > limit (limit语法和执行都在最后)
limit分页公式:
select * from 表 limit (page-1)*size,size;(要显示的页数为page,每页的条目数为size)
# 1.查询前五条员工信息select * from employees limit 5;# 2.查询第11条到第25条select * from employees limit 10,15# 3.有奖金的员工信息,并且显示出工资较高的前10名select * from employeeswhere commission_pct is not nullorder by salarylimit 10;
九、联合查询
定义:将多条查询语句的结果合并成一个结果。
语法:查询语句1 union 查询语句2 unin ... 查询语句n
应用场景:当要查询的结果来自多个没有连接关系的表,但查询的信息一致时,最适合使用union。
注意事项:
要求多条查询语句的查询列数是一致的要求多条查询语句查询的每一列的类型和顺序最好一致.union默认去重,如果使用union all可以关闭去重大多数情况下,union的查询效率比or高。# 1.查询部门编号>90或邮箱包含a的员工信息select * from employees where department_id>90 or email like '%a%';select * from employees where department_id>90 union  select * from employees where email like '%a%';
更多相关免费学习推荐:mysql教程(视频)
以上就是mysql精讲之一:dql数据查询语句的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product