ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

MySQL 子查询

2021-09-01 17:01:41  阅读:264  来源: 互联网

标签:employees 查询 MySQL 薪资 where id select


子查询(嵌套查询)

1. 理解
   一个查询语句中内嵌另一个完整的查询语句,被嵌套的语句 称为子查询 或者内查询
   外面的语句称为主查询 或者外查询
2. 语法
   select (子查询)
   from (子查询)
   where (子查询)

3. 特点
   1. 子查询 必须写在小括号中
   2. 子查询 优先执行  ,主查询需要用到子查询的结果
   3. 子查询结果
	单行子查询:结果只有一个 搭配的符号 =  > < >= <= <>
	多行子查询:结果多个     搭配的符号 in / not in / any(任一) / all (所有)

#案例1:查询薪资比'De Haan'的薪资高的员工信息
#step1: De Haan 的薪资
	select * from employees where last_name = 'De Haan';
#step2: 找到薪资比DeHaan薪资还要高的员工信息
	#select * from employees where salary > 17000;
	select * from employees where salary > 
      (select salary from employees where last_name = 'De Haan');


#案例2:查询location_id 是1400 或者 1700的部门中所有的员工的信息

select * from employees where department_id in 
(select department_id from departments where location_id = 1400 or location_id = 1700);


#案例3:查询其他工种中比工种为'IT_PROG'中的 所有员工薪资都低的员工薪资、名字
select * from employees where salary <
	(select min(salary) from employees where job_id = 'it_prog')

select * from employees where salary <
	(select salary from employees where job_id = 'it_prog' order by salary limit 1 )

select * from employees where salary < all
	(select salary from employees where job_id = 'it_prog')
		

查询的规则:
	1. 单表能实现 不用多表
 	2. 多表能实现 不用子查询
 	
	
子查询效率比较低。 	

标签:employees,查询,MySQL,薪资,where,id,select
来源: https://www.cnblogs.com/conglingkaishi/p/15215410.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有