SELECT
last_name
FROM
employees
WHERE
salary > ( SELECT salary FROM employees WHERE last_name = 'Abel' );
複製代碼
返回job_id和141號員工相同,salary比143號員工多的員工姓名、job_id和工資。
SELECT
last_name,
job_id,
salary
FROM
employees
WHERE
job_id = ( SELECT job_id FROM employees WHERE employee_id = 141 )
AND salary > ( SELECT salary FROM employees WHERE employee_id = 143 );
複製代碼
返回公司工資最少的員工的last_name、job_id和salary。
SELECT
last_name,
job_id,
salary
FROM
employees
WHERE
salary = ( SELECTmin( salary ) FROM employees );
複製代碼
查詢最低工資大於50號部門最低工資的部門id和其最低工資。
SELECT
department_id,
MIN( salary )
FROM
employees
GROUPBY
department_id
HAVINGmin( salary ) > ( SELECTmin( salary ) FROM employees WHERE department_id = 50 );
複製代碼
列子查詢:
返回location_id是1400或1700的部門中的全部員工姓名。
SELECT
last_name
FROM
employees
WHERE
department_id IN ( SELECTDISTINCT department_id FROM departments WHERE location_id IN ( 1400, 1700 ) );
複製代碼
SELECT
employee_id,
last_name,
job_id,
salary
FROM
employees
WHERE
salary < ANY ( SELECT DISTINCT salary FROM employees WHERE job_id = 'IT_PROG' ) and job_id != 'IT_PROG';
複製代碼
SELECT
employee_id,
last_name,
job_id,
salary
FROM
employees
WHERE
salary < ALL ( SELECTDISTINCT salary FROM employees WHERE job_id = 'IT_PROG' ) and job_id != 'IT_PROG';
複製代碼
行子查詢(用的較少):
查詢員工編號最小而且工資最高的員工信息。
SELECT * FROM employees
WHERE ( salary, employee_id ) = (( SELECTmax( salary ) FROM employees ),( SELECTmin( employee_id ) FROM employees )
);
複製代碼
select後面:
查詢每一個部門的員工個數。
SELECT d.*,( SELECTcount(*) FROM employees e WHERE e.department_id = d.department_id ) as'員工個數'FROM
departments d;
複製代碼
from後面:
查詢每一個部門的平均工資的工資等級。
SELECT
temp.department_id,
jg.grade_level
FROM
( SELECT department_id AS department_id, avg( salary ) AS`avg`FROM employees GROUPBY department_id ) temp
INNERJOIN ( SELECT grade_level, highest_sal, lowest_sal FROM job_grades ) jg ON temp.avg BETWEEN jg.lowest_sal
AND jg.highest_sal;
複製代碼
exists後面:
語法:
exists(完成的查詢語句)
結果:0或1
複製代碼
查詢有員工的部門名。
SELECT
department_name
FROM
departments d
WHEREEXISTS ( SELECT * FROM employees e WHERE d.department_id = e.department_id );
複製代碼
分頁查詢
語法:
SELECT 查詢列表
FROM 表 [jointype] JOIN 表2ON 鏈接條件
WHERE 篩選條件
GROUPBY 分組字段
HAVING 分組篩選條件
ORDERBY 排序字段
LIMIT 起始索引(從0開始),每頁顯示條數。
複製代碼
示例:查詢前5條員工信息。
SELECT
*
FROM
employees
LIMIT0,5;
複製代碼
union聯合查詢
概念:
將多條查詢語句的結果合併成一個結果。
語法:
查詢語句1
UNION
查詢語句2
……;
複製代碼
應用示例:
查詢部門編號>90或郵箱包含a的員工信息。
SELECT * FROM employees WHERE last_name LIKE'%a%'UNIONSELECT * FROM employees WHERE department_id > 90 ;
複製代碼