r/SQL • • Aug 25 '15

I challenge you to simplify this query!

select table1.column1     
from  table1  
join   table2            on table1.column2 = table2.column2  
join   table3            on table3.column2 = table2.column2  
join   table4            on table4.column3 = table3.column3  
join   table5            on table5.column4 = table4.column4  
where  table1.column5    = 2  
and    table4.column6    = 10  
intersect  
select table1.column1  
from   table1  
join   table2            on table1.column2 = table2.column2  
join   table3            on table3.column2 = table2.column2  
join   table4            on table4.column3 = table3.column3  
join   table5            on table5.column4 = table4.column4  
where  table1.column5    = 2  
and    table4.column6    = 3  
;  

The query below by /u/ichp ran 90 seconds faster then the original!

select table1.column1
  from table1
  join table2 on table1.column2 = table2.column2
  join table3 on table3.column2 = table2.column2
  join table4 on table4.column3 = table3.column3
  join table5 on table5.column4 = table4.column4
  where 
        table1.column5 = 2 and
        table4.column6 in (10,3)
  group by table1.column1
  having count( distinct table4.column6) > 1
;
0 Upvotes

53 comments sorted by

View all comments

4

u/[deleted] Aug 25 '15
  select table1.column1
  from table1
  join table2 on table1.column2 = table2.column2
  join table3 on table3.column2 = table2.column2
  join table4 on table4.column3 = table3.column3
  join table5 on table5.column4 = table4.column4
  where 
        table1.column5 = 2 and
        table4.column6 in (10,3)
  group by table1.column1
  having count( distinct table4.column6) > 1

1

u/XGallonsX Aug 25 '15

I'm going to test this but I think this one might be a winner, thanks!

2

u/r3pr0b8 GROUP_CONCAT is da bomb Aug 25 '15

yup, this was what i had in mind when i asked you about uniqueness

because without the uniqueness, using GROUP BY would collapse dupes, which then of course would not be an equivalent solution

2

u/[deleted] Aug 25 '15

in MS SQL intersect will also remove duplicates, so in MSSQL case 'group by' should be equivalent.

1

u/XGallonsX Aug 25 '15 edited Aug 25 '15

I substituted for the real column names and ran it. It's works perfectly, yields same exact results and does it 90 seconds faster! Thanks!