You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL中ANY子查询与INNER JOIN查询为何结果不同?差异解析

两个SQL查询的核心差异

这两个查询的本质区别在于是否返回重复的产品名称,具体拆解如下:

第一个查询:使用ANY子查询

SELECT ProductName 
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

这个查询的逻辑是:

  • 子查询先找出所有Quantity=10的订单明细对应的ProductID
  • 主查询检查Products表中的ProductID是否存在于子查询的结果集中
  • 只要匹配一次,就会返回该产品的名称,无论该产品在OrderDetails中有多少条符合条件的记录,最终结果里只会出现一次该产品名称

第二个查询:使用INNER JOIN

select productname
from products
inner join orderdetails on orderdetails.productid=products.productid
where orderdetails.quantity = 10;

这个查询的逻辑是:

  • 将Products和OrderDetails通过ProductID关联
  • 筛选出OrderDetails中Quantity=10的所有关联行
  • 如果某个产品在OrderDetails中有N条Quantity=10的记录,最终结果里就会重复N次该产品的名称

验证示例

假设OrderDetails表中,ProductID=1有3条Quantity=10的记录:

  • 第一个查询返回:ProductName(仅1行)
  • 第二个查询返回:ProductName(共3行,内容完全重复)

如果想让第二个查询的结果和第一个一致,只需给SELECT加上DISTINCT去重:

select DISTINCT productname
from products
inner join orderdetails on orderdetails.productid=products.productid
where orderdetails.quantity = 10;

内容的提问来源于stack exchange,提问作者Seyedmatin Seyedebrahimpour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:49:50