mysql - SQL中Exists的逻辑解释
问题描述
所以我有如下的订单和新订单表
**neworders**
+---------+------------+------------+--------------+------------+
| orderId | customerid | ordertotal | discountrate | orderdate |
+---------+------------+------------+--------------+------------+
| 1 | 3 | 1910.64 | 5.49 | 2019-12-03 |
| 2 | 4 | 150.89 | 15.33 | 2019-06-11 |
| 3 | 5 | 912.55 | 13.74 | 2019-09-15 |
| 4 | 7 | 418.24 | 14.53 | 2019-05-28 |
| 5 | 55 | 512.55 | 13.74 | 2019-06-15 |
| 7 | 57 | 118.24 | 14.53 | 2019-12-28 |
+---------+------------+------------+--------------+------------+
6 rows in set (0.013 sec)
**orders**
+---------+------------+------------+--------------+------------+
| orderId | customerid | ordertotal | discountrate | orderdate |
+---------+------------+------------+--------------+------------+
| 1 | 3 | 1910.64 | 5.49 | 2019-12-03 |
| 2 | 4 | 150.89 | 15.33 | 2019-06-11 |
| 3 | 5 | 912.55 | 13.74 | 2019-09-15 |
| 4 | 7 | 418.24 | 14.53 | 2019-05-28 |
| 5 | 55 | 512.55 | 13.74 | 2019-06-15 |
| 6 | 57 | 118.24 | 14.53 | 2019-12-28 |
+---------+------------+------------+--------------+------------+
6 rows in set (0.056 sec)
我想将存在与子查询一起使用。这是语法
select*from neworders where exists(select orderId from orders);
这是结果
+---------+------------+------------+--------------+------------+
| orderId | customerid | ordertotal | discountrate | orderdate |
+---------+------------+------------+--------------+------------+
| 1 | 3 | 1910.64 | 5.49 | 2019-12-03 |
| 2 | 4 | 150.89 | 15.33 | 2019-06-11 |
| 3 | 5 | 912.55 | 13.74 | 2019-09-15 |
| 4 | 7 | 418.24 | 14.53 | 2019-05-28 |
| 5 | 55 | 512.55 | 13.74 | 2019-06-15 |
| 7 | 57 | 118.24 | 14.53 | 2019-12-28 |
+---------+------------+------------+--------------+------------+
6 rows in set (0.001 sec)
我对输出或 orderId 为 7 感到很困惑,这里的逻辑是什么?
解决方案
exists(select orderId from orders)
如果子查询返回任何行,则为 true。由于子查询中没有WHERE
子句,它将返回orders
表中的所有行。因此,只要 表不为空,EXISTS
条件就为真。orders
既然这是真的,WHERE
主查询中的条件对于neworders
.
如果您只希望其中的行neworders
也在 中orders
,则需要在子查询中添加相关条件。
select *
from neworders AS n
where exists(
select orderId
from orders AS o
WHERE n.orderId = o.orderId
);
您也可以只使用JOIN
SELECT n.*
FROM neworders AS n
JOIN orders AS o ON n.orderId = o.orderId
推荐阅读
- postgresql - docker compose 错误“连接到 localhost:5432 被拒绝。”
- graphql - Pimcore:通过 API 获取名称包含给定字符串的所有资产
- ruby-on-rails - Rails Active Storage - 将文件从一个应用程序复制到另一个应用程序
- coq - 避免重复代码以在假设和目标中应用策略
- laravel - Laravel 中间件中的多个条件
- android - AAPT:错误:找不到资源 mipmap/ic_launcher_round
- typescript - 如何键入检查反应导航嵌套导航
- javascript - 在laravel 8中按组选择所有复选框
- android - 如何设置动态 JSON 的模态类,其中 JSON 的起始键在 android Kotlin 中发生变化
- r - R 安装失败