【问题标题】:Select values from a table that are not in a list SQL从表中选择不在列表 SQL 中的值
【发布时间】:2012-04-24 18:47:41
【问题描述】:

如果我输入:

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

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

有没有办法在不创建包含列表中所有值的新表的情况下做到这一点?

【问题讨论】:

  • 你用的是什么数据库(oracle?sql server?)

标签: sql


【解决方案1】:

根据你有多少值,你可以做几个联合。

见: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)

【讨论】:

  • 我昨天发现了它。这很漂亮。
  • 我得到了Incorrect syntax near the keyword 'where' - 必须给表命名,例如select * from (...) t where ....
【解决方案2】:

我通常使用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)

【讨论】:

    【解决方案3】:
    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
    

    这非常适合我没有临时表的问题#

    【讨论】:

      【解决方案4】:

      假设“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
      

      【讨论】:

        【解决方案5】:

        在 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-10
          • 1970-01-01
          • 2011-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多