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
相关产品推荐
相关产品推荐

