SQL NOT IN 的查询性能增强

SQL Query Performance Enhancement on NOT IN

假设我有一个查询需要查找购买了书 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'
)

这不是查询看起来效率不高,我可以做这个查询的任何增强?

尝试使用 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