【问题标题】:SELECT from a list of values从值列表中选择
【发布时间】:2020-09-24 12:08:57
【问题描述】:

所以这很简单:

Select Val from MyTable where Val not in ('100','200','300'....)
  1. 如何编写查询以便从列表中选择值。例如,我该如何做类似Select * from ('100','200','300'....) 这样的输出:

    100    
    200    
    300    
    ...
    
  2. 此外,我该如何做类似select * from ('100','200','300'....) that are not in MyTable.Val 列的事情?

【问题讨论】:

  • Val 是字符串类型('100')还是数字类型(100)?

标签: sql sql-server tsql subquery unpivot


【解决方案1】:

我该如何做一些不在 MyTable.Val 中的 select * from ('100','200','300'....)

您可以使用values() 构建一个包含值列表的派生表,然后使用not exists 过滤那些在表中找不到的:

select v.*
from (values (100), (200), (300)) v(val)
where not exists (select 1 from mytable t where t.val = v.val)

【讨论】:

  • where not exists (select 1 from mytable t where t.val = v.val)where v.val not in (select Val from MyTable) 有好处吗?
  • @VaibhavGarg:是的。首先,not exists 是空安全的,而not in 不是(如果mytable 中的任何valnull,就会发生奇怪的事情)。其次,not exists 的性能通常更优越(尤其是如果您在mytable(val) 上有索引)。
【解决方案2】:

第 1 部分

Select * from (values ('100'),('200'),('300')) v(val);

第 2 部分

Select * 
from
  (values ('100'),('200'),('300')) v(val)
where not exists (select 1 from myTable t where t.val=v.val);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多