1, select clients that have an invoice
可以用In或者join
select *
from clients
where client_id in (
select distinct client_id
from invoices
)
或者
SELECT *
FROM clients c1
JOIN (
SELECT DISTINCT client_id FROM invoices
) c2
ON c1.client_id = c2.client_id

我们还可以用今天要学的Exists运算符。如果客户ID非常多,可以节省效率,会妨碍最佳性能
select *
from clients c
where exists (
select distinct client_id
from invoices
where client_id=c.client_id
)
2,练习:找到没有被订购的产品,假设你有网站比如亚马逊,用in会返回很多结果集

答案:
如果用in
select *
from products
where product_id not in(
select product_id
from order_items
)
如果用exists
select *
from products p
where not exists (
select product_id
from order_items
where product_id =p.product_id
)

SQL查询优化:InvsExists操作在订单和客户数据中的应用,
本文介绍了在数据库查询中,使用IN和EXISTS运算符在查找关联客户和未订购产品时的区别。IN操作可能导致性能下降,而EXISTS用于更高效地检查是否存在匹配,特别当客户ID众多时。
1725

被折叠的 条评论
为什么被折叠?



