exists
exists型子查询后面是一个受限的select查询语句
exists子查询,如果exists后的内层查询能查出数据,则返回 TRUE 表示存在;为空则返回 FLASE则不存在。
注意:a为表dept的别名 b为employee的别名
select * from dept a where exists (select 1 from employee b where a.deptnu=b.deptnu);
mysql> select 1 from employee where 1=1;
+---+
| 1 |
+---+
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
+---+
13 rows in set (0.04 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| dept |
| employee |
| salgrade |
+----------------+
3 rows in set (0.01 sec)
mysql> select * from dept;
+--------+--------+------+
| deptnu | dname | addr |
+--------+--------+------+
| 10 | 研发部 | 北京 |
| 20 | 工程部 | 上海 |
| 30 | 销售部 | 广州 |
| 40 | 财务部 | 深圳 |
+--------+--------+------+
4 rows in set (0.01 sec)
mysql> select * from employee;
+-------+--------+--------+------+------------+----------+--------+
| empno | ename | job | mgr | hiredate | sal | deptnu |
+-------+--------+--------+------+------------+----------+--------+
| 1004 | 猪八戒 | 经理 | 1009 | 2001-04-02 | 29750.00 | 20 |
| 1006 | 猴子 | 经理 | 1009 | 2011-05-01 | 28500.00 | 30 |
| 1007 | 张飞 | 经理 | 1009 | 2011-09-01 | 24500.00 | 10 |
| 1008 | 诸葛亮 | 分析师 | 1004 | 2017-04-19 | 30000.00 | 20 |
| 1013 | 林俊杰 | 分析师 | 1004 | 2011-12-03 | 30000.00 | 20 |
| 1002 | 牛魔王 | 销售员 | 1006 | 2018-02-20 | 16000.00 | 30 |
| 1003 | 程咬金 | 销售员 | 1006 | 2017-02-22 | 12500.00 | 30 |
| 1005 | 后裔 | 销售员 | 1006 | 2011-09-28 | 12500.00 | 30 |
| 1010 | 韩信 | 销售员 | 1006 | 2018-09-08 | 15000.00 | 30 |
| 1012 | 安琪拉 | 文员 | 1006 | 2011-12-03 | 9500.00 | 30 |
| 1014 | 甄姬 | 文员 | 1007 | 2019-01-23 | 7500.00 | 10 |
| 1011 | 妲己 | 文员 | 1008 | 2018-05-23 | 11000.00 | 20 |
| 1001 | 小乔 | 文员 | 1013 | 2018-12-17 | 8000.00 | 20 |
+-------+--------+--------+------+------------+----------+--------+
13 rows in set (0.02 sec)
mysql> select * from dept a where exists (select 1 from employee b where a.deptnu=b.deptnu);
+--------+--------+------+
| deptnu | dname | addr |
+--------+--------+------+
| 10 | 研发部 | 北京 |
| 20 | 工程部 | 上海 |
| 30 | 销售部 | 广州 |
+--------+--------+------+
3 rows in set (0.03 sec)
mysql> select * from dept a where not exists (select 1 from employee b where a.deptnu=b.deptnu);
+--------+--------+------+
| deptnu | dname | addr |
+--------+--------+------+
| 40 | 财务部 | 深圳 |
+--------+--------+------+
1 row in set (0.04 sec)