繁体   English   中英

编写此SQL查询的最有效方法是什么?

[英]What is the most effecient way to write this SQL query?

我有两个ID清单。 列表A和列表B。这两个列表实际上都是SQL查询的结果(分别为QUERY A和QUERY B)。

我想通过删除列表A中的ID(如果它们出现在列表B中)来“过滤”列表A。

因此,例如,如果列表A看起来像这样:

1,2,3,4,7

清单B看起来像这样:

2,7

那么“过滤后的”列表A应该删除了ID 2和7,因此应如下所示:

1 3 4

我想编写一个这样的SQL查询(当然是伪代码):

SELECT id FROM(QUERYA)as temp_table where id not in(QUERYB)

使用经典SQL:

select [distinct] number
from list_a
where number not in (
    select distinct number from list_b
);

我不确定方是否要删除重复项(删除方括号或整个单词),因此将第一个"distinct"放在方括号中。 万一您的DBMS无法优化IN子句,则应保留第二个"distinct"

沿着以下路线进行左连接可能会更快(措施,不要猜测):

select [distinct] list_a.number from list_a
left join list_b on list_a.number = list_b.number
where list_b.number is null;

同样处理"[distinct]"

查询:

select id 
from ListA
where id not in (
    select id 
    from ListB)

会给您想要的结果。

我不确定哪种方法最好。 就像我以前的印象一样,性能可能会有所不同,取决于情况和桌子的大小。

1。

select id 
from ListA
where id not in (
    select id 
    from ListB)

2。

select ListA.id 
from ListA
left join ListB on ListA.id=ListB.id
where ListB.id is null

3。

select id 
from ListA
where not exists (
    select * 
    from ListB where ListB.id=ListA.id)

2)通常应该是最快的,因为它确实是内部联接而不是子查询。

有人可能会建议3)而不是1),因为它使用了“存在”而不从表中读取数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM