2012-04-24 2 views
7

내가 입력 한 경우 :선택 값은

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

내가 목록에없는 테이블에서 항목을 얻을 수 있습니다. 반대를 원합니다 : 테이블에없는 목록에서 값을 가져옵니다. 예를 들어, 테이블에 'Test1'및 'Test3'값이있는 이름의 열이있는 경우이를 ('Test1', 'Test2', 'Test3')과 비교하고 Test2를 반환합니다. 다른 예로 테이블이 비어 있으면 목록의 모든 항목 (Test1, Test2 및 Test3)을 반환합니다.

목록의 모든 값을 사용하여 새 테이블을 만들지 않고도이 작업을 수행 할 수 있습니까?

+0

이 임시 테이블 번호없이 내 문제에 대한 완벽한 (오라클? SQL 서버를?) – aquinas

+0

출력을 제공합니다. – Trinculo

답변

7

보유하고있는 값의 개수에 따라 몇 가지 유니언을 사용할 수 있습니다.

참조

: 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) 
+2

좋은 sqlfiddle 서비스 – Anton

+2

나는 그것을 어제 발견했다. 꽤 매끄럽다. – aquinas

+0

감사 aqunias, 귀하의 솔루션을 잘 근무했습니다. – Trinculo

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 
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 

내가 sqlite3를 사용하고

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

(2 row(s) affected) 

testName 
-------- 
Test2 

(1 row(s) affected) 
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 

어떤 데이터베이스 것은 당신이 사용하는