开发者

COALESCE not working with join

I'm sure someone has a better idea about this so here goes - I have a table with a bunch of ids (@tbLink) that represent rows in other tables. I'm trying to express here

declare @tbLink table (linkid int, identitytypeid int, 
                      itemid int, categoryid int,parentid int)
de开发者_开发百科clare @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

My results are:

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

But I was expecting row 1 to be 'ProgramA' not 'Module1' - am I missing something here? Is this the proper use of COALESCE also?

Cheers

Mike


both rows have a item ID of 1.

i think you may want to join them on the category id AND the item id., change ProgramA to have a programid of 1, and in your join:

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


maybe you should consider a different design. Fo what i can guess you could try these changes:

--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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜