使用左外连接进行慢查询并且为空条件

mic*_*huk 2 sql postgresql

我有一个简单的查询(postgresql,如果这很重要),它检索some_user的所有项目,不包括她在心愿单上的项目:

select i.* 
from core_item i 
left outer join core_item_in_basket b on (i.id=b.item_id and b.user_id=__some_user__)
where b.on_wishlist is null;
Run Code Online (Sandbox Code Playgroud)

以上查询运行在~50000ms(是的,数字是正确的).如果我删除"b.on_wishlist为null"条件或使其"b.on_wishlist is not null",则查询将在大约50ms内运行(相当大的变化).

该查询具有更多的连接和条件,但这是无关紧要的,因为只有这一个减慢了它.

有关数据库大小的一些信息:

  • core_items有~10,000条记录
  • core_user有~5000条记录
  • core_item_in_basket有~2.000
  • 记录(其中约50%的on_wishlist = true,其余为null)

我在这两个表上没有任何索引(除了id和外键).

问题是:我该怎么做才能让这个更快?我自己今晚有一些想法可以查看,但如果可能的话,我希望你们能帮忙.

谢谢!

Mla*_*dic 5

尝试使用不存在:

select i.* 
from   core_item i 
where  not exists (select * from core_item_in_basket b where i.id=b.item_id and b.user_id=__some_user__)
Run Code Online (Sandbox Code Playgroud)