如何加入几个表?

时间:2013-02-08 11:22:03

标签: sql sql-server

在MS SQL Server上,我想在一个选择中加入一些表。

表:

追踪:

Segment_ID | Track_INFO

SEGMENT_ID:

Segment_ID | Road_ID

道:

Road_ID | Road_INFO

所以我想从Track和Road表中选择信息。我知道如何加入两个表:

    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

但是如何在我的情况下制作JOIN?

4 个答案:

答案 0 :(得分:5)

试试这个:

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

而且,如果你有空标记,也许你需要LEFT加入......

答案 1 :(得分:2)

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

您也可以根据您想要的行为将“内部联接”更改为“左联接”

答案 2 :(得分:2)

试试这个:

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

答案 3 :(得分:2)

尽量避免现在已经过时的表连接如下所示。

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

更好的加入表格的方法是使用INNER JOIN(或JOIN),LEFT JOINRIGHT JOIN,具体取决于您的要求; < / p>

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

以下是关于 JOINS 的一些好graphical examples以及他们带来的结果