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.
Author |
Topic |
jpogorman
Starting Member
2 Posts |
Posted - 2007-10-11 : 10:33:56
|
Hi,This may or may not be basic but I can't get my head around it.I want to select from table1 all the ids for a particular userid that are not contained in table2...table1id, useridtable2fkidFor example,table1id, userid1, user12, user13, user2table2fkid13I want to select all ids for user1 that are not contained in table 2 so I would get id 2.I hope that is understandable.Thank you,JP |
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2007-10-11 : 10:52:05
|
[code]-- Prepare sample datadeclare @t1 table( id int, userid varchar(20))declare @t2 table( fkid int)insert @t1select 1, 'user1' union allselect 2, 'user1' union allselect 3, 'user2'insert @t2select 1 union all select 3-- Actual queryselect id from @t1 t1 left join @t2 t2 on t1.id = t2.fkidwhere t2.fkid is null[/code]Harsh AthalyeIndia."The IMPOSSIBLE is often UNTRIED" |
 |
|
Dallr
Yak Posting Veteran
87 Posts |
Posted - 2007-10-11 : 11:07:43
|
You could use a subquery in the WHERE clause but using a LEFT JOIN will be faster. Try the following.SELECT T1.ID, T1.UserIDFROM Table1 T1 LEFT JOIN Table2 T2 ON T1.ID = T2.FkIDWHERE T2.fkID IS NULL AND T1.userid = 'user1' Dallr |
 |
|
jpogorman
Starting Member
2 Posts |
Posted - 2007-10-11 : 11:37:47
|
Thats exactly what I was looking for. Thank you both very much. I would be a while coming up with that myself.JP |
 |
|
Dallr
Yak Posting Veteran
87 Posts |
Posted - 2007-10-11 : 13:31:59
|
No problem Harsh and I were happy to assist!Dallr |
 |
|
|
|
|
|
|