【问题标题】:Best way to check that a list of items exists in an SQL database column?检查 SQL 数据库列中是否存在项目列表的最佳方法?
【发布时间】:2010-10-01 05:39:04
【问题描述】:

如果我有物品清单,请说

apples
pairs
pomegranites

并且我想识别 SQL DB 表的“fruit”列中不存在的任何内容。

  • 快速性能是主要问题。
  • 需要可移植到不同的 SQL 实现。
  • 输入列表可以包含任意数量的条目。

我能想到几种方法,我想我会把它扔在那里,看看你们的想法。

【问题讨论】:

  • 哦,我也不关心表中的项目是什么顺序,只关心每个项目是否存在。

标签: sql list exists


【解决方案1】:

由于您选择的水果列表可以任意长,我建议如下:

create table FruitList (FruitName char(30))
insert into FruitList values ('apples'), ('pears'), ('oranges')

select * from FruitList left outer join AllFruits on AllFruits.fruit = FruitList.FruitName
where AllFruits.fruit is null

左外连接应该比“不在”或其他类型的查询快得多。

【讨论】:

  • +1 但 FWIW 您需要单独用括号括起来的每个元组:VALUES ('apples'), ('pears'), ('oranges'), ...
  • 谢谢@Bill。我不怎么使用 VALUES,应该先检查我的参考资料。固定。
  • 可能是最好的选择。如果你不想创建表,你可以创建一个表变量来代替做同样的事情,当你的查询结束时它会被销毁。
  • 当 values 子句只允许您一次执行一个时,偷偷摸摸地解决插入一堆测试记录 insert mytable(field) select 'apples' union all select 'Pears' union all select 'oranges '
【解决方案2】:

将搜索列表变成一个类似于 '|fruit1|fruit2|...fruitn|' 的字符串并制作你的 where 子句:

where
  @FruitListString not like '%|' + fruit + '|%'

或者,将上述字符串解析为临时表或表变量,然后执行where not in (select fruit from temptable)。根据您要搜索的项目数和要搜索的项目数,此方法可能会更快。

【讨论】:

【解决方案3】:
if exists(select top 1 name from fruit where name in ('apples', 'pairs', 'pomegranates'))
  PRINT 'one exists'

【讨论】:

  • 这只是说存在一个水果,而不是不存在的水果列表。
  • 我看不出他说他需要桌子上剩下的水果在哪里,只是其中一个是否存在。
  • 抱歉,我需要识别列表中但表中不存在的水果。
猜你喜欢
  • 2015-01-10
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多