从表中选择不在列表SQL中的值

时间:2012-04-24 18:47:41

标签: sql

如果我输入:

SELECT name FROM table WHERE name NOT IN ('Test1','Test2','Test3');

我可以从表中获取不在列表中的条目。我想做相反的事情:从列表中获取不在表中的值。例如,如果table有一个名为name的列,其值为'Test1'和'Test3',我想将其与('Test1','Test2','Test3')进行比较并返回Test2。或者作为另一个例子,如果表是空的,则返回列表中的所有内容:Test1,Test2和Test3。

有没有办法在不创建包含列表中所有值的新表的情况下执行此操作?

5 个答案:

答案 0 :(得分:9)

根据你拥有的价值,你可以做几个工会。

请参阅:http://www.sqlfiddle.com/#!5/0e42f/1

select * from (
  select 'Test 1' thename union
  select 'Test 2' union 
  select 'Test 3'
)
where thename not in (select name from foo)

答案 1 :(得分:1)

我通常使用SELECT 'FOO' AS COL UNION SELECT 'BAR'等,然后使用左连接的标准惯用语并检查NULL以查找缺少的元素。

CREATE TABLE #YourTable(
name nvarchar(50)
)

insert into #YourTable (name) values ('Test1'), ('Test3')

-- ALL
select * from #YourTable

--MISSING
select t1.* from (
  select 'Test1' testName
  union select 'Test2'
  union select 'Test3') as t1
  left outer join #YourTable yt on t1.testName = yt.name
  where yt.name is null

DROP TABLE #YourTable

提供输出

name
--------------------------------------------------
Test1
Test3

(2 row(s) affected)

testName
--------
Test2

(1 row(s) affected)

答案 2 :(得分:1)

Select a.value from (
SELECT 'testvalue' value UNION
SELECT 'testvalue2' value UNION
SELECT 'testvalue3' value UNION
SELECT 'testvalue4' value UNION
) a
left outer join othertable b
on a.value=b.value
where b.value is null

对于没有临时表#

的问题,这是完美的

答案 3 :(得分:0)

假设“othertable”占有问题......

 select a.value from 
    (select 'test1' value
     union
     select 'test2' value
     union 
     select 'test3' value) a
       left outer join othertable b
         on a.value=b.value
      where b.value is null

答案 4 :(得分:0)

在SQL Server中,以下查询效果很好。

SELECT v.val FROM (VALUES 
    ('A'), 
    ('B'), 
    ('C'), 
    ('D'), 
    ('E') 
) v (val)
LEFT JOIN dbo.TABLE_NAME t ON t.COLUMN_NAME = v.val
WHERE t.COLUMN_NAME IS NULL;

可以找到以下输出:

val
-------
A
B
C
D