views:

73

answers:

2

Im a little confused about whether should I use a nested Subquery Or JOINS with distinct !! which one of these will perform better and faster ?

any suggestions to do this query without distinct ?!?

SELECT distinct TOP(20) e.*, u1.UserName As Sender,
u2.UserName As Receiver, u1.Avatar AS SenderPic  
FROM Friends f INNER JOIN Users u 
ON(u.Id = f.SenderId OR u.Id = f.ReceiverId) AND State = 'ok' 
INNER JOIN Events e 
ON(f.SenderId = e.SenderId OR f.SenderId = e.ReceiverId 
OR f.ReceiverId = e.SenderId OR f.ReceiverId = e.ReceiverId) 
INNER JOIN Users u1 
ON (e.SenderId = u1.Id) 
INNER JOIN Users u2 
ON (e.ReceiverId = u2.Id) 
WHERE u.Id = @id;
+2  A: 

The OR's in the INNER JOIN conditions will slow it down, but ultimately knowing which approach will be the fastest is highly dependent on the number of rows in each table. I recommend attempting both for comparison.

MPelletier
lets say we have a million record as a result .. is it Effective to use my way !! or should I replace it with subQuery !
Rawhi
Joining very large tables is always demanding, so a subquery or two might reduce the dataset you're working with. But I really suggest you take the time and test both.
MPelletier
A: 

It depends on the DBMS. My experience on Oracle is that there isn't much difference but you can use the SQL Explain statement to measure the costs. On your SELECT it is important that you have indices set on all the Id's. Also I am not quite sure why you need the distinct at all but to judge about this I would need to know the whole DB models cardinalities.

Jürgen Hollfelder
how can I find 'SQL Explain' !?
Rawhi
SQL Execution Plan is what he means - you can find it in SQL Server Management Studio when executing your query.
Sam
@Sam: Thanks for clarifying at the beginning it was not clear which DBMS being used.
Jürgen Hollfelder