Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Problem in query

Author  Topic 

keyursoni85
Posting Yak Master

233 Posts

Posted - 2009-12-17 : 11:39:54
Hello,
I have two tables.. MainTab And SubType
-------
MainTab
-------
mainTabId mType
1 m1
2 m2
3 m3
4 m4
-------
SubType (for storing sub type information UserId wise)
-------
subTabId mainTabId subType userID
1 1 s1 1
2 2 s2 2
3 3 s3 3

Now here i want subType Information with UserId Filter and mainTab Tables Rows which not include row which are included in subType

OutPut (FOR USERID = 1)
---------
subTabId mainTabId mType
1 1 k1
0 2 k2
0 3 k3
0 4 k4


I have tried out but i am Getting duplicate with my query
I have used below query

Select s.SubTabId, m.mainTabId, m.mType From SubType s
INNER JOIN mainTab m
ON s.mainTabId = m.mainTabId
Where s.userId = 2
UNION
Select 0, mainTabId, mType From mainTab
Order By SubTabId DESC

THIS GIVES ABOVE output with two duplicate rows for "k1" mType

Plz help..

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2009-12-17 : 11:56:47
It's true probably

Select s.SubTabId, m.mainTabId, m.mType From SubType s
INNER JOIN mainTab m
ON s.mainTabId = m.mainTabId
Where s.userId = 2
UNION
Select 0, mainTabId, mType From mainTab as m
where not exists
(select *
from SubType as s
where userID = 2
and s.mainTabId = m.mainTabId)
Order By SubTabId DESC

Go to Top of Page

keyursoni85
Posting Yak Master

233 Posts

Posted - 2009-12-17 : 12:02:22
thanks but i have used this way using "not in"
is there any other optimized way to do the same....
Go to Top of Page

keyursoni85
Posting Yak Master

233 Posts

Posted - 2009-12-17 : 12:16:54
is there any other way OR CTE.. we can use
any suggestion for the same query.. ?
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2009-12-19 : 09:41:46
In fact you need LEFT/RIGHT OUTER JOIN.
Try this one:

declare @m table (mainTabId int, mType char(2))
insert @m values
(1, 'k1'),
(2, 'k2'),
(3, 'k3'),
(4, 'k4')
declare @s table (subTabId int, mainTabId int, subType char(2), userID int)
insert @s values
(1, 1, 's1', 1),
(2, 2, 's2', 2),
(3, 3, 's3', 3)

select isnull(d.SubTabId,0) as SubTabId,
m.mainTabId,
m.mType
from @m as m
left outer join
(Select s.SubTabId,
m.mainTabId,
m.mType
From @s as s
inner join @m as m
on s.mainTabId = m.mainTabId
Where s.userId = 1) as d
on m.mainTabId=d.mainTabId


Go to Top of Page
   

- Advertisement -