EXISTS 运算符
EXISTS 运算符用于判断查询子句是否有记录,如果有一条或多条记录存在返回 True,否则返回 False。
SQL EXISTS 语法
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
演示数据库
在猿变手册教程中,我们将使用 yuanbian 样本数据库。
下面是选自 "goods" 表的数据:
+----------+-----------------------------+-------------+
| goods_id | goods_name | goods_price |
+----------+-----------------------------+-------------+
| 10 | 猿变手册之C++ | 35 |
| 11 | 猿变手册之Python | 25 |
| 12 | 猿变手册之疯狂前端 | 30 |
+----------+-----------------------------+-------------+
下面是选自"orders" 表的数据:
+----------+--------------+----------+--------------+----------------+---------------------+
| order_id | order_no | goods_id | order_amount | order_quantity | create_date |
+----------+--------------+----------+--------------+----------------+---------------------+
| 1 | 201503120001 | 10 | 1000 | 10 | 2015-03-12 09:00:04 |
| 2 | 201503120002 | 12 | 1300 | 12 | 2015-03-12 17:23:10 |
| 3 | 201503130001 | 11 | 2400 | 22 | 2015-03-13 10:30:12 |
| 4 | 201503130002 | 12 | 2500 | 15 | 2015-03-13 11:00:05 |
| 5 | 201503130003 | 10 | 1400 | 15 | 2015-03-13 14:54:00 |
| 6 | 201503140001 | 12 | 2100 | 12 | 2015-03-14 11:34:00 |
+----------+--------------+----------+--------------+----------------+---------------------+
SQL EXISTS 示例
如果订单金额>2000的商品。注意exits子句的where条件部分的关联条件
我们使用下面的 SQL 语句:
select * from goods
where exists
(select * from orders where order_amount> 2000 and orders.goods_id=goods.goods_id)
执行以上 SQL 输出结果如下:
+----------+-----------------------------+-------------+
| goods_id | goods_name | goods_price |
+----------+-----------------------------+-------------+
| 11 | 猿变手册之Python | 25 |
| 12 | 猿变手册之疯狂前端 | 30 |
+----------+-----------------------------+-------------+
NOT EXISTS示例
查询"2015-03-12"当天没有订单的商品
select *
from goods
where not exists
(select * from orders where date(create_date)='2015-03-12' and orders.goods_id=goods.goods_id)
执行以上 SQL 输出结果如下:
+----------+-----------------------+-------------+
| goods_id | goods_name | goods_price |
+----------+-----------------------+-------------+
| 11 | 猿变手册之Python | 25 |
+----------+-----------------------+-------------+
讨论区