Kliver Max
Kliver Max

Reputation: 5299

How to JOIN several tables?

On MS SQL Server i want to join some tables in one select.

Tables:

Track:

Segment_ID | Track_INFO

Segment_ID:

Segment_ID | Road_ID

Road:

Road_ID | Road_INFO

So i want to select information from Track and Road tables. I know how to join two tables:

    SELECT  

    Segment_ID = T1.Segment_ID,
    Track = T1.Track,
    --Road_ID = Segment_ID.Road_ID


FROM dbo.Track T1,dbo.Road T2
LEFT JOIN Segment_ID Segment_ID ON Segment_ID.Segment_ID = T1.Segment_ID
--LEFT JOIN Road Road_ID ON Road.Road_ID = Segment_ID.Road_ID

But how to make JOIN in my case?

Upvotes: 0

Views: 713

Answers (4)

Kaf
Kaf

Reputation: 33839

Try to avoid table joining as below which is obsolete now.

FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id

Better way of joining table is using INNER JOIN (or JOIN), LEFT JOIN, RIGHT JOIN etc depending on your requirement like;

SELECT * --Or you can get required list of columns using table aliases (t,s,r)
FROM dbo.Track t JOIN dbo.Segment_ID s ON t.Segment_ID = s.Segment_ID
         JOIN dbo.Road r ON s.Road_ID = r.Road_ID

Here are some good graphical examples about JOINS and what results they bring

Upvotes: 2

Roman Badiornyi
Roman Badiornyi

Reputation: 1539

Try this:

SELECT Track.Track_INFO, Road.Road_INFO
FROM Track 
INNER JOIN Segment_ID ON Segment_ID.Segment_ID = Track.Segment_ID
INNER JOIN Road ON Segment_ID.Road_ID = Road.RodaID

And also, maybe you need LEFT join if you have Null marks...

Upvotes: 5

CloudyMarble
CloudyMarble

Reputation: 37576

Try this:

SELECT  t.*, r.* 
FROM track t 
INNER JOIN segment s ON t.Segment_ID = s.Segment_ID 
INNER JOIN road r ON s.Road_ID = s.Road_ID

Upvotes: 2

Noxthron
Noxthron

Reputation: 492

select * 
from Track inner join Segment_ID on Track.Segment_ID = Segment_ID.Segment_ID
 inner join Road on Segment_ID.Road_ID = Road.Road_ID

also you can change "inner join"s to "left join"s depending on the behaviour you want

Upvotes: 2

Related Questions