Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Question about JOINs and table order

Author  Topic 

Xercister
Starting Member

6 Posts

Posted - 2013-03-19 : 22:08:58
So I've been reading up on JOINS and for the most part I get it. However I do have a few questions that I am not finding answers to.

1. If you have 3 tables in your database.

Table 1, Table 2, Table 3

Table 1 relates to Table 2
Table 1 relates to Table 3
Table 2 does not relate to Table 3

If you wanted to use these tables together can you do something like this?

SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T2.xx

If not, why not?

2. Order of the ON clause in the JOIN syntax.

If you're joining Table 1 and Table 2 I would assume you would use this.

FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T2.xx = T1.xx.

Does it matter what order the fields are that you're joining them on?

Is that the same as this?

FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx

Thanks for the help in advance!

chadmat
The Chadinator

1974 Posts

Posted - 2013-03-20 : 00:29:31
1. Yes
2. Yes you can, order doesn't matter.

-Chad
Go to Top of Page

UnemployedInOz
Yak Posting Veteran

54 Posts

Posted - 2013-03-21 : 01:59:59
This doesnt look right
SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T2.xx

It should be

SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T3.xx -- Should be T3.xx not T2.xx
Go to Top of Page

chadmat
The Chadinator

1974 Posts

Posted - 2013-03-21 : 02:10:55
quote:
Originally posted by UnemployedInOz

This doesnt look right
SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T2.xx

It should be

SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T3.xx -- Should be T3.xx not T2.xx



Yes, you are correct, I missed that.

-Chad
Go to Top of Page

Xercister
Starting Member

6 Posts

Posted - 2013-03-21 : 07:37:56
quote:
Originally posted by UnemployedInOz

This doesnt look right
SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T2.xx

It should be

SELECT *
FROM Table 1 AS T1
JOIN Table 2 AS T2 ON T1.xx = T2.xx
JOIN TABLE 3 AS T3 ON T1.xx = T3.xx -- Should be T3.xx not T2.xx



Ah yea, gotta love those typos.. Thanks for catching that.
Go to Top of Page
   

- Advertisement -