tags:

views:

892

answers:

8

When I'm joining three or more tables together by a common column, I'd write my query like this:

SELECT *
FROM   a, b, c
WHERE  a.id = b.id
AND    b.id = c.id

a colleague recently asked my why I didn't do explicit Join Transitive Closure in my queries like this:

SELECT *
FROM   a, b, c
WHERE  a.id = b.id
AND    b.id = c.id
AND    c.id = a.id

are the really any advantages to this? Surely the optimiser can imply this for itself?

edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @Stu for cleaning it up

+2  A: 

No this syntax stems from the days before joins were in the language. Not sure of the problems associated with it, but there are definitely language constructs that are more supported for jointing tables.

Nick Berardi
+1  A: 

If you look at it from a mathematical point of view, your examples should yeild the same results.

a = b = c

So your first example would yield the same results as the second, so no need to do the extra work.

GateKiller
+1  A: 

I just want to say that this kind of joining is the devils work.
Just think about it; the conditions for joining and filtering gets mixed together in the where statement.
What happens when you need to join across 20 tables and filter on 15 values?

Again, just my $.02

Lars Mæhlum
+1  A: 

In Microsoft SQL the query plans for these two queries are identical - they are executed in the same way.

Keith
+1  A: 

You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.

These days that entire syntax is going out anyway.

Lasse V. Karlsen
+1  A: 

This is filthy, evil legacy syntax. You write this as

Select
  *  -- Oh, and don't ever use *, either
From
  A 
  Inner Join B On A.ID = B.ID
  Inner Join C On B.ID = C.ID
Stu
A: 

That syntax has its uses though ... there are times when you find you need to join two tables on more than one field

Conrad
You can do that in regular join syntaxFROM table1 t1.JOIN table2 t2 on t1.field1 = t2.field1 and t.field2 = t2.field2
HLGEM
A: 

This question is similar to this one here with a very in-depth explanation:

http://stackoverflow.com/questions/397089/sql-question-from-joel-spolsky-article

The short answer is, that the explicit declaration of the transitiv property may speed the query up. This is because query optimization is not a trivial task and some SQL servers might have problems with it.

sdfx