MySQL数据库js css htmlSQL

Select进阶查询·子查询

2023-01-28  本文已影响0人  技术老男孩

一、子查询定义:

二、命令格式:

Where命令之后:

SELECT 表头名列表 FROM 库.表 WHERE 表头名 判断符号 (SELECT查询命令)

Having命令之后:

SELECT 表头名列表 FROM 库.表 WHERE 筛选条件 HAVING 判断符号 (SELECT查询命令)

From命令之后:

SELECT 表头名列表 FROM (SELECT查询命令) WHERE 筛选条件;

Select命令之后:

SELECT 表头名列表 (SELECT查询命令) FROM 库.表 WHERE 筛选条件;

三、使用案例:

where 命令之后:
# 先查看人事部和财务部的 部门id
mysql> select dept_id from departments  
where dept_name in ('人事部', '财务部');
      
# 再查询人事部和财务部员工信息
mysql> select dept_id , name  from employees 
where dept_id in ( 
  select dept_id from departments  
  where dept_name in ('人事部', '财务部') 
);
# 先把100号员工的基本工资查出来
mysql> select basic from salary  
where year(date)=2018 
and 
month(date)=12 and employee_id=100;  

# 再查看比100号员工工资高的
mysql> select  *  from salary 
where year(date)=2018 and month(date)=12 
and 
basic  >  (
  select basic from salary 
  where year(date)=2018 
  and 
  month(date)=12 and employee_id=100
);
having 命令之后:
# 统计开发部 员工总人数
mysql> select count(*) from employees 
where dept_id = (
  select dept_id from departments 
  where dept_name="开发部"
);

# 统计每个部门总人数 
mysql> select dept_id,count(name) from employees
group by dept_id;

# 输出总人数比开发部总人数少的部门名及总人数 
mysql> select dept_id,count(name) as total from employees 
group by dept_id 
having total < (
  select count(name) from employees  
  where dept_id=(
    select dept_id from departments 
    where dept_name='开发部'
  )
);
from 命令之后:
mysql> select dept_id,dept_name,employee_id,name,email 
from (
  select d.dept_name,e.* from departments as d 
  inner join employees as e 
  on 
  d.dept_id=e.dept_id 
) as tmp_table 
where dept_id=3;
select 命令之后:
#显示部门表中的所有列表
mysql> select d.*  from departments as d;   

#查询每个部门的人数
mysql> select  d.*,(
  select count(name) from employees as e  
  where d.dept_id=e.dept_id
) as 总人数 from departments as d;
上一篇下一篇

猜你喜欢

热点阅读