在 mysql 中,in 和 exists 都用于查询中,以根据子查询中是否存在行来过滤数据。然而,它们的工作方式不同,在它们之间进行选择会影响查询性能。让我们通过解释和实践示例来分解它们的差异。
描述:
in 子句用于根据列的值是否与列表或子查询中的任何值匹配来过滤行。它检查内部查询中的匹配值,并将它们与外部查询进行比较。
性能:
当子查询返回少量记录时,in 子句通常很有效。但是,如果子查询返回较大的数据集,in 可能会变慢。
语法:
select columns from table where column in (subquery);
描述:
exists 子句检查子查询返回的行是否存在。如果子查询返回任何行,则 exists 的计算结果为 true,并且外部查询将继续进行。它不关心行的内容,只关心行是否存在。
性能:
对于大型数据集,exists 通常速度更快,因为一旦找到匹配项,它就会停止处理。这使得在处理返回多行的子查询时变得高效。
语法:
select columns from table where exists (subquery);
让我们考虑两个表:客户和订单。
customer_id | customer_name |
---|---|
1 | john doe |
2 | jane smith |
3 | alice brown |
order_id | customer_id | order_total |
---|---|---|
1 | 1 | 200 |
2 | 1 | 150 |
3 | 2 | 300 |
我们希望找到所有至少下过一笔订单的客户。
select customer_name from customers where customer_id in (select customer_id from orders);
说明:
结果:
|客户名称 |
|--------------|
|约翰·多伊 |
|简·史密斯 |
select customer_name from customers c where exists (select 1 from orders o where o.customer_id = c.customer_id);
说明:
结果:
|客户名称 |
|--------------|
|约翰·多伊 |
|简·史密斯 |
返回值:
效率:
用例:
假设我们有:
使用 in 查询:
select customer_name from customers where customer_id in (select customer_id from orders);
使用 exists 查询:
select customer_name from customers c where exists (select 1 from orders o where o.customer_id = c.customer_id);
以上就是SQL 中的 IN 与 EXISTS:了解性能和用法的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号