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 |
|
CaelDorwin
Starting Member
3 Posts |
Posted - 2009-09-16 : 15:14:34
|
| I have two tables. The fields of Table 1 are:T1ID (pk)NameDescriptionT2IDTable 2:T2ID (pk)NameThe names in Table 1 are expected to repeat across all T2ID's. Meaning if I have 10 entries in Table2, EACH distinct name in Table 1 should have a row with name, description and the appropriate T2ID.Over time the data in the table has gotten out of alignment (shocker?) and I am trying to write a query that will take each Name from Table 1 and figure out which of the T2ID's are missing.If that is not clear I can provide more detail but I am just plain stuck on how to get the right combination of joins/in's/not in's to make the result happen the way I need it to.Any help would be appreciated. |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-09-16 : 15:23:03
|
You mean you have T2IDs in table1 which don't exist in table2? Those are called orphaned rows. Typically a Foreign Key constraint would be on table1 (referencing table2) to not allow that.select t1.*from table1 t1left outer join table2 t2 on t2.T2ID = t1.T2IDwhere t2.T2ID is null Be One with the OptimizerTG |
 |
|
|
CaelDorwin
Starting Member
3 Posts |
Posted - 2009-09-16 : 17:12:56
|
| No I mean I have T1 data that looks like (T1ID, Name, Description, T2ID) Values:1000, Benjamin, Sales Guy 1, 50001001, Benjamin, Sales Guy 1, 50011002, Benjamin, Sales Guy 1, 50031003, Tom, Sales Guy 2, 50001003, Tom, Sales Guy 2, 50011004, Tom, Sales Guy 2, 50021005, Tom, Sales Guy 2, 5004And T2 data that looks like (T2ID, Name):5000, Northeast5001, Southeast5002, Midwest5003, Northwest5004, SouthwestI need to see that Benajamin is missing from T2ID 5002 and 5004 and that Tom is missing from T2ID 5003.Hope that helps what I am getting at. |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-09-17 : 01:39:09
|
| select t2.* from t2 left join t1 on t1.t2id = t2.t2idwhere t1.t2id is nullselect * from t2 where t2id not in (select t2id from t1)select * from t2 where not exists (select * from t1 where t2id = t2.t2id) |
 |
|
|
CaelDorwin
Starting Member
3 Posts |
Posted - 2009-09-17 : 11:11:25
|
| At some point or another in the data each t2id is used so these queries all return no rows.Where I am at currently is needing a query that does something like this (written in english; not syntax):For each t1.Name: select t2.* where t2.t2id not in (select t1.t2id where t1.Name = [Name currently being tested])LoopThanks for all of your help so far! |
 |
|
|
|
|
|
|
|