#返回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
);
#多行子查询
#多行子查询的操作符
/*
IN 等于列表中的任意一个
ANY 需要和单行比较操作符一起使用,和子查询返回的某一个值比较(任意)
ALL 需要和单行比较操作符一起使用,和子查询返回的所有值比较
SOME 实际上是ANY的别名,和ANY作用相同,一般常使用ANY
*/
#非法子查询
SELECT employee_id,last_name
FROM employees
WHERE salary = (
SELECT MIN(salary)
FROM employees
GROUP BY department_id
);
#IN
SELECT employee_id,last_name
FROM employees
WHERE salary IN (
SELECT MIN(salary)
FROM employees
GROUP BY department_id
);
#ANY/ALL
#返回其他job_id中比job_id为'IT_PROG'部门任一工资低的员工的员工号,姓名,job_id以及salary
SELECT employee_id,last_name,job_id,salary
FROM employees
WHERE job_id <> 'IT_PROG'
AND salary < ANY (
SELECT salary
FROM employees
WHERE job_id = 'IT_PROG'
);
SELECT salary
FROM employees
WHERE job_id = 'IT_PROG'
-- ----------------------
#MYSQL中,聚合函数不能嵌套
SELECT MIN(AVG(salary))
FROM employees
GROUP BY department_id;
#第九章:约束
/*
1.基础知识
1.1为什么要约束?为了保证数据的完整性
1.2什么叫约束?对表中字段的限制
1.3约束的分类
角度一:约束的字段个数
单列约束 vs 多列约束
角度二:约束的作用范围
列级约束:将此约束声明在对应字段的后面
表级约束:在表中所有字段都声明完,在所有字段的后面声明的约束
角度三:约束的作用(或功能)
(1)NOT NULL
(2)UNIQUE 唯一性约束
(3)PRLMARY KEY 主键约束
(4)FOREIGE KEY 外键约束
(5)CHECK 检查约束
(6)DEFAULT 默认约束
1.4如何添加/删除约束
CREATE TABLE 时添加约束
ALTER TABLE 时添加约束,删除约束
2 如何查看表中的约束
*/
SELECT * FROM information_schema.
table_constraints
WHERE table_name = 'employees';
#NOT NULL 非空约束 只能用列表约束,不能用表级约束
CREATE TABLE dbtest;
USE dbtest;
#CREATE TABLE 时添加约束
CREATE TABLE test1(
id INT NOT NULL,
last_name VARCHAR(10) NOT NULL,
email VARCHAR(15),
salary INT
)
DESC test1;
INSERT INTO test1(id,last_name,email,salary)
VALUES(1,'TOM','TOM@126.com',5000);
INSERT INTO test1(id,last_name,email,salary)
VALUES(2,'NULL','TOM1@126.com',5000);