我有两张桌子让我们说“Table1”和“Table2”
表1
ID AccountId BranchId otherColumn
----------- ---------- ---------- -----------
1 15 58 data
2 22 62 data
3 31 89 data
4 49 45 data
. . . .
. . . .
. . . .
. . . .
. . . .
表2
ID fromAccount toAccount ExcludeAccount IncludeAccount FromBranch ToBranch IncludeBranch ExcludeBranch
----------- ---------- ---------- ----------- ---------- --------- ------------ -------------- ------------
1 1 90 89,34,3 101 30 100 205,207,250 35,40
1 5 67 90 22 50 70,90 20
2 7 4 3 5 200
2 1 5 7 10 16 9
3 5 89 6,7 200 55 243 34 35,200,201,234
现在我想使用 Table1
中的表达式从 Table1 中选择所有数据我有将逗号分隔文本转换为表格
的函数select data from dbo.split('23,45,2', ',')
这将返回
data
------
23
45
2
第1行的我想要的输出是
ID AccountId BranchId otherColumn
----------- ---------- ---------- -----------
. 1 . data
. 2 . data
. 4 . data
. 5 . data
. 6 . data
. 7 . data
. 8 . data
. . . .
. . . .
. 33 . .
. 35 . .
. . . .
. 88 . .
. 90 . .
. 101 . .
. . 30 .
. . 31 .
. . . .
. . 34 .
. . 36 .
. . . .
我已创建查询以获取具有这两个表关系的数据但它总是不返回行
这是我的查询
select * from Table1
inner join Table2 on Table1.AccountId between Table2.fromAccount and Table2.toAccount
and Table1.AccountId not in (select data from dbo.split(Table2.ExcludeAccount, ','))
and Table1.AccountId in (select data from dbo.split(Table2.IncludeAccount, ','))
and Table1.BranchId between Table2.FromBranch and Table2.ToBranch
and Table1.BranchId not in (select data from dbo.split(Table2.ExcludeAccount, ','))
and Table1.BranchId in (select data from dbo.split(Table2.IncludeAccount, ','))
我的问题是,为什么它总是返回没有数据是我的查询中的任何错误或我做错了方式
答案 0 :(得分:1)
not in
通常不是您想要的子查询。如果子查询返回的任何值为NULL
,则根本没有任何内容通过过滤器。相反,习惯使用not exists
。
例如,而不是:
not in (select data from dbo.split(Table2.ExcludeAccount, ','))
使用:
not exists (select 1
from dbo.split(Table2.ExcludeAccount, ',') s(p)
where Table1.BranchId = s.p
)
您可能还遇到数据类型问题,但SQL Server应正确转换它们。