0

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

表:

追踪:

Segment_ID | Track_INFO

Segment_ID:

Segment_ID | Road_ID

路:

Road_ID | Road_INFO

所以我想从 Track and 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

但是在我的情况下如何加入?

4

4 回答 4

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 加入......

于 2013-02-08T11:27:28.727 回答
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

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

于 2013-02-08T11:26:06.693 回答
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
于 2013-02-08T11:26:26.267 回答
2

尽量避免如下表加入,现在已经过时了。

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

根据您的要求,更好的连接表的方法是使用INNER JOIN(或JOINLEFT JOINRIGHT JOIN等;

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的很好的图形示例以及它们带来的结果

于 2013-02-08T11:36:52.920 回答