Mysql之子查詢

  • 含義:
    出現在其他語句中的select語句,稱爲子查詢或內查詢,外部的查詢語句,稱爲主查詢或外查詢。
  • 分類:
    按子查詢出現的位置:

    select 後面:
        僅僅支持標量子查詢
    from 後面
        支持表子查詢
    where或having後面
        標量子查詢
        列子查詢
        行子查詢
    exists後面(相關子查詢)
        表子查詢

    按結果集的行列數不同:

    標量子查詢(結果集只有一行一列)
    列子查詢(結果集有一列多行)
    行子查詢(結果集有一行多列)
    表子查詢(結果集一般爲多行多列)

一、where或having後面

特點:

子查詢放在小括號內
子查詢一般放在條件的右側
標量子查詢,一般搭配單行操作符使用
> < >= <= = <>
列子查詢,一般搭配着多行操作符使用
IN、ANY/SOME、ALL

標量子查詢

  1. 查詢誰的工資比Abel高

    select salary from employees where last_name='Abel' // 一行一列 11000
    select last_name,salary from employees where salary > (select salary from employees where last_name='Abel')
  2. 查詢最低工資大於50號部門最低工資的部門id和其最低工資

    #查詢50號部門最低工資
    select min(salary) from employees where department_id=50 // 2100
    #按條件查詢
    select department_id,min(salary) from employees GROUP BY department_id HAVING min(salary)> (select min(salary) from employees where department_id=50)

列子查詢

  1. 返回location_id 是1400或1700的部門中所有員工姓名

    #查詢所有部門id
    select department_id from departments where location_id=1400 or location_id=1700

    image.png

    #查詢員工姓名是上面查詢部門中的某一個
    select last_name from employees where department_id in (select department_id from departments where location_id=1400 or location_id=1700)

    image.png

列子查詢

  1. 查詢員工編號最小,並且工資最高的員工信息

    select * from employees where (employee_id, salary) = (select min(employee_id), max(salary) from employees)

一、select 後面

標量子查詢

  1. 查詢每個部門員工個數

    select *, (select count(*) from employees e where e.department_id = d.department_id)  from departments d

一、from後面

表子查詢

  1. 查詢每個部門的平均工資的工資等級
SELECT ag_dep.*, g.grade_level FROM (SELECT avg(salary) as ag, department_id FROM employees GROUP BY department_id) ag_dep
JOIN job_grades g ON ag_dep.ag BETWEEN lowest_sal AND highest_sal

一、exists後面(相關子查詢)

語法:

exists(完整的查詢語句)
結果:1或0
  1. 查詢每個部門員工個數
select department_name from departments d where EXISTS (select * from employees e where e.department_id = d.department_id)

子查詢中select 後面可以用employees表中的任何字段或*

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章