views:

40

answers:

2

I have a query where I use a sub query, and I would like to rewrite into a join, to have better performance.

The subquery uses DISTINCT as there are many records, and the problem I have is that they end up multiple times in the join when I use the join.

So how do I rewrite a query like this to use join:

SELECT * 
FROM   table1 a 
       JOIN table2 b 
         ON b.field1 = a.field1 
WHERE  b.field3 = 1531 
       AND a.field4 = 0 
       AND a.field5 IN (SELECT DISTINCT field5 
                        FROM   table3 
                        WHERE  field6 = 172) 
+2  A: 

Something like:

SELECT * 
FROM   table1 a 
       JOIN table2 b ON b.field1 = a.field1 
       JOIN ( SELECT DISTINCT field5 
                        FROM   table3 
                        WHERE  field6 = 172 ) C 
       ON C.field5 = a.field5

WHERE  b.field3 = 1531 AND a.field4 = 0 

It's hard to say without seeing the actual data, so if this doesn't work, please let me know.

Tim
isn't after JOIN be a table?
Srinivas Reddy Thatiparthy
@Srinivas - if you are asking if that's legal syntax, yes, you can join to the result of another select query as though it were a table. Not sure if that's ANSI-92 or not though; I'm looking on my own MS SQL Server code.
Tim
the query is correct, after JOIN there is a table that is enclosed in a (), it's the subquery, that computes the table.
Pentium10
A: 

Relocate the DISTINCT keyword to the SELECT clause in the main query e.g.

SELECT DISTINCT a.*, b.*
FROM   table1 a 
       JOIN table2 b 
         ON b.field1 = a.field1 
       JOIN table3 c
         ON a.field5 = c.field5 
WHERE  b.field3 = 1531 
       AND a.field4 = 0 
       AND c.field6 = 172;

You should review the use of SELECT * in your query i.e. not best practise.

onedaywhen