上的sql查询性能增强不在

ppcbkaq5  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(371)

假设我有一个查询,需要查找购买了图书a但没有购买图书b的用户。
典型的sql查询可以是:

select u.user_name
from User u 
join Purchase p on u.id=p.user_id
join Book b on p.purchase_item=b.id
where b.name='book_A'
and user_name not in
(
select u.user_name
from User u 
join Purchase p on u.id=p.user_id
join Book b on p.purchase_item=b.id
where b.name='book_B'
)

这个不在查询看起来效率不高,有什么增强我可以做这个查询吗?

35g0bw71

35g0bw711#

尝试使用exists子句而不是in子句-

SELECT u.user_name
  FROM Purchase p
  JOIN Book b ON p.purchase_item=b.id
  JOIN User u ON u.id=p.user_id
 WHERE b.name='book_A'
   AND NOT EXISTS (SELECT NULL
                     FROM Purchase p2
                     JOIN Book b ON p.purchase_item=b.id
                    WHERE b.name='book_B'
                      AND p.user_id = p2.user_id)

除此之外,你可以尝试在下面的列上建立索引-

User - id
Purchase - user_id, purchase_item
Book - id, name

相关问题