sql - 有没有更有效的方法在这个特定的上下文中编写我的过滤器?
问题描述
我正在使用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
...
有没有更有效的方法来编写我的过滤器?
解决方案
一种选择使用not exists
and 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)
)
当列表中的列和/或值的数量增加时,这比您的原始查询更好地扩展 - 尽管这不一定更有效。
身份证 | n1 | n2 | n3 | n4 | n5 | n6 --: | -: | -: | -: | -: | -: | -: 103 | 6 | 12 | 25 | 27 | 28 | 33
推荐阅读
- google-apps-script - 在 GAS 中调用工作表函数
- python - 如何阻止 Kivy 在 RecycleView 中自动选择模数项?
- arrays - 在 Swift 中的 for 循环中存储新数组
- python - 如何在python中的字典中搜索多个值?
- reactjs - 如何在 reactJS 环境中查找、添加、删除 MongoDB 中的数据库条目
- oracle - oracle 中的多个 SID
- sql - 获得在sql中完成的所有计数总和的正确方法
- ruby-on-rails - RAILS - 强制在 ActiveRecord 模型中用于 .save 和 .update 的条件
- laravel - 在 Laravel 中找不到验证请求类
- javascript - 使用引导程序设置我的导航栏及其子项的链接