sql server - SQL join format - nested inner joins -
i have following sql statement in legacy system i'm refactoring. abbreviated view purposes of question, returning count(*) time being.
select count(*) table1 inner join table2 inner join table3 on table2.key = table3.key , table2.key2 = table3.key2 on table1.differentkey = table3.differentkey
it generating large number of records , killing system, please explain syntax? , can expressed in other way?
- table1 contains 419 rows
- table2 contains 3374 rows
- table3 contains 28182 rows
edit:
suggested reformat
select count(*) table1 inner join table3 on table1.differentkey = table3.differentkey inner join table2 on table2.key = table3.key , table2.key2 = table3.key2
for readability, restructured query... starting apparent top-most level being table1, ties table3, , table3 ties table2. easier follow if follow chain of relationships.
now, answer question. getting large count result of cartesian product. each record in table1 matches in table3 have x * y. then, each match between table3 , table2 have same impact... y * z... result 1 possible id in table 1 can have x * y * z records.
this based on not knowing how normalization or content tables... if key primary key or not..
ex: table 1 diffkey other val 1 x 1 y 1 z table 3 diffkey key key2 tbl3 other 1 2 6 v 1 2 6 x 1 2 6 y 1 2 6 z table 2 key key2 other val 2 6 2 6 b 2 6 c 2 6 d 2 6 e
so, table 1 joining table 3 result (in scenario) 12 records (each in 1 joined each in 3). then, again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count returned.
so, now, take , expand based on 1000's of records , see how messed-up structure choke cow (so-to-speak) , kill performance.
select count(*) table1 inner join table3 on table1.differentkey = table3.differentkey inner join table2 on table3.key =table2.key , table3.key2 = table2.key2
Comments
Post a Comment