SQL Server - 使用表值函数构建查询

时间:2017-06-21 10:06:05

标签: sql-server

我有以下表格结构: 的 tblMapping

map_id   | name  | parent_id
1          A       0
2          B       1
3          C       2
4          D       2
5          E       4

tblEditableContent

id   | map_id   | desc_id   | isExcluded
1      1          0           0
2      4          0           1

在此表中,tblEditableContentdesc_id=0表示允许显示给定map_id(其所有子项)下的所有元素,desc_id=1表示选择了节点本身。 我还有一个表值函数(映射),它将为给定的map_id构建节点,类似于下面的结果:

代表select * from dbo.mapping(1)

map_id   | name
1          A
2          B
3          C 
4          D 
5          E

代表select * from dbo.mapping(4)

map_id   | name
4          D
5          E

现在,为了任务和要求。 我尝试创建以下结果:

map_id   | name   | desc_id   | isExcluded
1          A        0           0
2          B        0           0
3          C        0           0

同时,如果我们将desc_idtblEditableContent的值从0更改为1,则输出应为:

map_id   | name   | desc_id   | isExcluded
1          A        0           0
2          B        0           0
3          C        0           0
5          E        0           0

以下是我迄今为止尝试过的内容:

select ca.map_id, ca.name, ec.desc_id, ec.isExcluded from tblEditableContent ec
CROSS APPLY (
    Select * From dbo.mapping(ec.map_id)
) ca 
where ec.isExcluded = 0
order by ca.map_id

1 个答案:

答案 0 :(得分:0)

您可以尝试以下查询:

select 
    ec.* 
from tblEditableContent ec
join
(
select 
ca.map_id as map_id,
MAX(ec.isExcluded) as isExcluded
from  tblEditableContent ec
    OUTER APPLY 
        (
        Select map_id from dbo.mapping(ec.map_id) where ec.desc_id =0 or (ec.desc_id =1 and map_id=ec.map_id)
        ) ca 
group by  ca.map_id
)ca
on ca.isExcluded=0 and ec.map_id=ca.map_id