Mysql选择不在表中的地方

BCS*_*BCS 52 mysql join not-exists

我有2个表(A和B)具有相同的主键.我想选择A中的所有行而不是B中的行.以下工作:

select * from A where not exists (select * from B where A.pk=B.pk);
Run Code Online (Sandbox Code Playgroud)

但是看起来很糟糕(A中只有10万行~2秒,B中只有3-10k行)

有没有更好的方法来运行它?也许作为左联盟?

select * from A left join B on A.x=B.y where B.y is null;
Run Code Online (Sandbox Code Playgroud)

在我的数据上,这似乎运行得稍快(~10%),但总的来说呢?

Nic*_*rdi 55

我认为你最后的陈述是最好的方式.你也可以试试

SELECT A.*    
from A left join B on 
    A.x = B.y
    where B.y is null
Run Code Online (Sandbox Code Playgroud)

  • 这没有任何意义。当 By 为 null 时,Ax=By 永远不会为 true。您将获得 A 的所有行,而不仅仅是 B 中没有匹配行的行。 (2认同)
  • @Bill,但它的工作原理!另外,它与上面列出的第二个语句完全相同. (2认同)
  • @Smok“我认为你最后的说法是最好的方法。你也可以尝试......”〜你的不一样吗? (2认同)

Bil*_*win 35

我以第二个例子的格式使用查询.连接通常比相关子查询更具可伸缩性.