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 |
asafg
Starting Member
39 Posts |
Posted - 2008-09-29 : 04:10:53
|
I have three tables each with unique ID.I need to remove the records in all tables when the ID does not exist in all three tables.Is there a way to do that in a more intelligent way than minedelete form table2 where id not in (select id from table1)delete form table3 where id not in (select id from table1)delete form table1 where id not in (select id from table2)delete form table3 where id not in (select id from table2)delete form table1 where id not in (select id from table3)delete form table2 where id not in (select id from table3)I'm a beginner and I'm not even sure that what I wrote does the job correctly.ThanksAsaf |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-09-29 : 04:18:57
|
[code]1.delete t from table1 tinner join(select idfrom(select id,1 as cat from table1 union all select id,2 from table2 union all select id,3 from table3)tgroup by idhaving count(distinct cat)<3)ron r.id=t.id2.delete t from table2 tinner join(select idfrom(select id,1 as cat from table1 union all select id,2 from table2 union all select id,3 from table3)tgroup by idhaving count(distinct cat)<3)ron r.id=t.id3.delete t from table3 tinner join(select idfrom(select id,1 as cat from table1 union all select id,2 from table2 union all select id,3 from table3)tgroup by idhaving count(distinct cat)<3)ron r.id=t.id[/code] |
|
|
asafg
Starting Member
39 Posts |
Posted - 2008-09-29 : 05:00:13
|
It's beautiful... I think that the following change:select idinto #T1 --the changefrom(select id,1 as cat from table1 union all select id,2 from table2 union all select id,3 from table3)tgroup by idhaving count(distinct cat)<3)ron r.id=t.id...can improve the performance for big tables (saving the repeating select queries)Anyway I'll check if the change improve your code which I like very much.ThanksAsaf |
|
|
|
|
|
|
|