MySQL-子查询(DQL 结束)

054-where后面使用子查询

什么是子查询

  1. select语句中嵌套select语句就叫做子查询。
  2. select语句可以嵌套在哪里?
    1. where后面、from后面、select后面都是可以的。
sql 复制代码
select ..(select)..
from ..(select)..
where ..(select)..
where后面使用子查询

案例:找出高于平均薪资的员工姓名和薪资。

错误的示范:

sql 复制代码
select ename,sal from emp where sal > avg(sal);

可以使用子查询:

sql 复制代码
select ename, sal from emp where sal>(select avg(sal) from emp);
from后面使用子查询

小窍门 :from后面的子查询可以看做一张临时表。

案例:找出每个部门的平均工资的等级。

sql 复制代码
select d.*, s.grade from (select deptno, avg(sal) avgsal from emp group by deptno) d join salgrade s on d.avgsal between s.losal and hisal;
select后面使用子查询

案例:查询员工属于哪个部门

sql 复制代码
select e.ename, (select d.dname from dept d where d.deptno=e.deptno) as dname from emp e;
select e.ename, d.dname from emp e join dept d on e.deptno=d.deptno;

057-exist与not exist的使用及与in的区别

案例:看一下谁下过单

in

sql 复制代码
select distinct customer_id from t_order;
select * from t_customer where customer_id in (select distinct customer_id from t_order);

exist

sql 复制代码
select * from t_customer c where exists(select * from t_order t where c.customer_id=t.customer_id);

in和exists区别

IN 和 EXISTS 都是用于关系型数据库查询的操作符。不同之处在于:

  1. IN 操作符是根据指定列表中的 来判断是否满足条件,而 EXISTS 操作符则是根据子查询的结果是否有返回记录集来判断。
  2. EXISTS 操作符通常比 IN 操作符更 ,尤其是在子查询返回记录数很大的情况下。因为 EXISTS 只需要判断是否存在符合条件的记录,而 IN 操作符需要比对整个列表,因此执行效率相对较低。
  3. IN 操作符可同时匹配多个值 ,而 EXISTS 只能匹配一组条件

058-union&union all

不管是union还是union all都可以将两个查询结果集进行合并。

union会对合并之后的查询结果集进行去重操作。

union all是直接将查询结果集合并,不进行去重操作。(union all和union都可以完成的话,优先选择union all,union all因为不需要去重,所以效率高一些。)


案例:查询工作岗位是MANAGER和SALESMAN的员工

sql 复制代码
select ename, job from emp where job in ('MANAGER', 'SALESMAN');

select ename, job from emp where job='MANAGER'
union all
select ename, job from emp where job='SALESMAN';

以上案例采用or也可以完成,那or和union all有什么区别?考虑走索引优化之类的选择union all,其它选择or。

两个结果集合并时,列数量要相同:

059-通用的分页SQL- limit

  1. limit作用:查询第几条到第几条的记录。通常是因为表中数据量太大,需要分页显示。
  2. limit语法格式:
    1. limit 开始下标, 长度
    2. limit 长度(默认从0开始)
  3. 案例:查询员工表前5条记录
sql 复制代码
select * from emp limit 5;
select * from emp limit 0, 5;

DQL: Data QueryLanguage

DQL 结束:)

相关推荐
拉不拉斯4 分钟前
Goweb---Gorm操作数据库(二)
数据库·mysql·gorm·钩子函数·goweb
小旺不正经13 分钟前
mongoDB快速上手
数据库·mongodb
EPSDA15 分钟前
Java中的Junit、类加载时机与机制、反射、注解及枚举
java·数据库·junit
暮毅1 小时前
二、初步编写drf API
数据库·django·sqlite·drf
@技术无疆1 小时前
【Python】FeinCMS:轻量级且可扩展的Django内容管理系统
数据库·python·django·sqlite·pip·pygame·httpx
小安运维日记1 小时前
Linux云计算 |【第四阶段】RDBMS1-DAY2
linux·运维·服务器·mysql·云计算
敲代码的小王!2 小时前
mybatisplus介绍以及使用(下)
java·数据库·mybatis
傻Q爱6 小时前
.NET 控制台应用程序连接 MySQL 数据库实现增删改查
mysql·c#