COALESCE不与加入合作

时间:2011-01-12 08:06:12

标签: sql join coalesce

我确信有人对此有了更好的了解,所以这里 - 我有一个带有一堆id(@tbLink)的表,表示其他表中的行。我想在这里表达

declare @tbLink table (linkid int, identitytypeid int, 
                      itemid int, categoryid int,parentid int)
declare @tbCat table (categoryid int, name varchar(20))
declare @tbId table (typeid int, typename varchar(20))
declare @tbDomain table (domainid int, domainname varchar(20))
--
declare @tbModule table (moduleid int, modulename varchar(20))
declare @tbProgram table (programid int, programname varchar(20))


INSERT INTO @tbLink VALUES (1, 1, 1, 1, 1)
INSERT INTO @tbLink VALUES (2, 1, 1, 2, 1)

INSERT INTO @tbCat VALUES (1, 'Program')
INSERT INTO @tbCat VALUES (2, 'Module')

INSERT INTO @tbId VALUES (1, 'Domain')
INSERT INTO @tbId VALUES (2, 'Group')

INSERT INTO @tbDomain VALUES (1, 'DEV')

INSERT INTO @tbModule VALUES (1, 'Module1')
INSERT INTO @tbProgram VALUES (2, 'ProgramA')


select t.*, i.typename, c.name, d.domainname, COALESCE(m.modulename, p.programname) 
as objectname from @tbLink t
inner join
@tbId i on t.identitytypeid = i.typeid
inner join
@tbCat c on t.categoryid = c.categoryid
inner join
@tbDomain d on t.parentid = d.domainid
left join
@tbModule m on m.moduleid = t.itemid
left join
@tbProgram p on p.programid = t.itemid

我的结果是:

1   1   1   1   1   Domain  Program DEV Module1
2   1   1   2   1   Domain  Module  DEV Module1

但是我期待第1行是'ProgramA'而不是'Module1' - 我在这里遗漏了什么?这是COALESCE的正确使用吗?

干杯

麦克

2 个答案:

答案 0 :(得分:0)

两行的商品ID均为1。

我认为您可能希望将他们加入类别ID和商品ID。,将ProgramA更改为编程为1,并在您的加入中:

left join
@tbModule m on t.categoryid  = 2 AND m.moduleid = t.itemid
left join
@tbProgram p on t.categoryid  = 1 AND p.programid = t.itemid

答案 1 :(得分:0)

也许您应该考虑不同的设计。我可以猜测你可以试试这些变化:

--declare @tbModule table (moduleid int, modulename varchar(20))
--declare @tbProgram table (programid int, programname varchar(20))
declare @tbItems table (itemid int, categoryid int, itemname varchar(20)) 

... 
--INSERT INTO @tbModule VALUES (1, 'Module1')
--INSERT INTO @tbProgram VALUES (2, 'ProgramA')
INSERT INTO @tbItems VALUES (1, 1, 'Module1')
INSERT INTO @tbItems VALUES (1, 2, 'ProgramA')

select t.*, i.typename, c.name, d.domainname, its.itemname 
as objectname from @tbLink t
inner join
@tbId i on t.identitytypeid = i.typeid
inner join
@tbCat c on t.categoryid = c.categoryid
inner join
@tbDomain d on t.parentid = d.domainid
left join @tbItems its on its.categoryid = t.categoryid AND its.itemid = t.itemid 
--@tbModule m on m.moduleid = t.itemid
--left join
--@tbProgram p on p.programid = t.itemid