2009-01-13 44 views
6

如果我有一個項目的名單,說檢查SQL數據庫列中是否存在項目列表的最佳方法?

apples 
pairs 
pomegranites 

,我想找出任何不中的SQL數據庫表中的「果實」列存在。

  • 快速性能是主要關注的問題。
  • 需要通過不同的SQL實現進行移植。
  • 輸入列表可以包含任意數量的條目。

我可以想出幾種方法來做到這一點,以爲我會把它扔到那裏,看看你們的想法。

+0

哦,我不在乎表中物品的順序是什麼,只是每個物品是否存在。 – Brabster 2009-01-13 20:19:46

回答

12

因爲你是從選擇水果的列表可以任意長,我建議如下:

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
if exists(select top 1 name from fruit where name in ('apples', 'pairs', 'pomegranates')) 
    PRINT 'one exists' 
+0

這隻表示存在一個水果,而不是不存在的水果列表。 – 2009-01-13 20:25:12

+0

我沒有看到他說他需要表中其餘的水果,只是它是否存在。 – scottm 2009-01-13 20:28:43

+0

對不起,我需要確定列表中的水果,但不存在於表格中。 – Brabster 2009-01-13 20:31:44

3

將搜索列表變成看起來像'| fruit1 | fruit2 | ... fruitn |'的字符串並讓你的where子句:

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

或者,將上述字符串解析爲臨時表或表變量並執行where not in (select fruit from temptable)。根據您要搜索的項目數量和搜索的項目數量,此方法可能會更快。

相關問題