首页 > 解决方案 > 有没有更有效的方法在这个特定的上下文中编写我的过滤器?

问题描述

我正在使用SQL Server 2014并且我的数据库中有一个表 ( t1),其中包含一个数字列表 (n1 到 n6)。摘录如下:

Id   n1   n2   n3   n4   n5   n6
100  3    10   26   31   35   39
101  1    3    11   22   36   40
102  10   19   20   30   39   40
103  6    12   25   27   28   33
...

假设我想通过排除存在数字 3 和 19 的行来过滤掉这个表,我的过滤代码将如下所示:

Select * from t1

WHERE [n1] not in (3,19)
AND [n2] not in (3,19)
AND [n3] not in (3,19)
AND [n4] not in (3,19)
AND [n5] not in (3,19)
AND [n6] not in (3,19)

预期输出:

Id   n1   n2   n3   n4   n5   n6
103  6    12   25   27   28   33
...

有没有更有效的方法来编写我的过滤器?

标签: sqlsql-servertsqlselectunpivot

解决方案


一种选择使用not existsand values()

select t.*
from mytable t
where not exists (
    select 1
    from (values(n1), (n2), (n3), (n4), (n5), (n6)) x(n)
    where n in (3, 19)
)

当列表中的列和/或值的数量增加时,这比您的原始查询更好地扩展 - 尽管这不一定更有效。

DB Fiddle 上的演示

身份证 | n1 | n2 | n3 | n4 | n5 | n6
--: | -: | -: | -: | -: | -: | -:
103 | 6 | 12 | 25 | 27 | 28 | 33

推荐阅读