-- 建表
CREATE TABLE emp(
empno INT,
ename VARCHAR(50),
job VARCHAR(50),
mgr INT,
hiredate DATE,
sal DECIMAL(7,2),
comm decimal(7,2),
deptno INT
) ;
-- 插入表数据
INSERT INTO emp values(7369,'SMITH','CLERK',7902,'1980-12-17',800,NULL,20);
INSERT INTO emp values(7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600,300,30);
INSERT INTO emp values(7521,'WARD','SALESMAN',7698,'1981-02-22',1250,500,30);
INSERT INTO emp values(7566,'JONES','MANAGER',7839,'1981-04-02',2975,NULL,20);
INSERT INTO emp values(7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250,1400,30);
INSERT INTO emp values(7698,'BLAKE','MANAGER',7839,'1981-05-01',2850,NULL,30);
INSERT INTO emp values(7782,'CLARK','MANAGER',7839,'1981-06-09',2450,NULL,10);
INSERT INTO emp values(7788,'SCOTT','ANALYST',7566,'1987-04-19',3000,NULL,20);
INSERT INTO emp values(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000,NULL,10);
INSERT INTO emp values(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500,0,30);
INSERT INTO emp values(7876,'ADAMS','CLERK',7788,'1987-05-23',1100,NULL,20);
INSERT INTO emp values(7900,'JAMES','CLERK',7698,'1981-12-03',950,NULL,30);
INSERT INTO emp values(7902,'FORD','ANALYST',7566,'1981-12-03',3000,NULL,20);
INSERT INTO emp values(7934,'MILLER','CLERK',7782,'1982-01-23',1300,NULL,10);
-- 建表
CREATE TABLE dept(
deptno INT,
dname varchar(14),
loc varchar(13)
);
-- 插入表数据
INSERT INTO dept values(10, 'ACCOUNTING', 'NEW YORK');
INSERT INTO dept values(20, 'RESEARCH', 'DALLAS');
INSERT INTO dept values(30, 'SALES', 'CHICAGO');
INSERT INTO dept values(40, 'OPERATIONS', 'BOSTON');
any,in,some,all都应用于子查询,是子查询中的关键字。
简单理解:
in:等于其中一个就为真;
any与some:其中任意一个条件满足就为真;
all:满足所有条件就为真;
其中any与some用法一致,any,some,all可以与比较符一起使用(=等于,< 小于,> 大于,<> 不等于,<= 小于等于,>=大于等于),且any,some和all必须与一个比较操作符一起使用。
下面通过实例来看下具体用法:
-- 1.查询和scott或CLARK相同部门的员工姓名ename和雇用日期hiredate
-- 为了方便看结果,我们查看scott,CLARK及和他们同部门的员工的全部信息
SELECT * FROM emp WHERE deptno IN(SELECT deptno FROM emp WHERE ename="scott" OR ename="CLARK");
SELECT * FROM emp WHERE deptno = ANY(SELECT deptno FROM emp WHERE ename="scott" OR ename="CLARK");
SELECT * FROM emp WHERE deptno = SOME(SELECT deptno FROM emp WHERE ename="scott" OR ename="CLARK");
结果都为:
-- 可以看出语句in 与“=any”是相同的,都表示为其中任意一个。语句some是any的别名,用法相同。
-- 2.查询和scott与CLARK不同部门的员工信息
SELECT * FROM emp WHERE deptno NOT IN(SELECT deptno FROM emp WHERE ename="scott" OR ename="CLARK");
SELECT * FROM emp WHERE deptno<>ALL(SELECT deptno FROM emp WHERE ename="scott" OR ename="CLARK");
结果都为:
可以看出: not in 与 “<>all”等价,都表示全都不。