2012-11-24 128 views
1

我有兩個表連接,第一個是這樣的:SQL Server 2008中選擇兩個表

[比較]

  • ID(INT)
  • Car_Id1(INT)
  • Car_Id2(INT)
  • 蛞蝓(字符串)
  • 時間戳

第二個:

[VehicleSpecs]

  • ID(INT)
  • 年份(INT)
  • 製作(字符串)
  • 模型(字符串)

我有這個疑問

SELECT TOP 100 * 
FROM [Comparsions] 
WHERE 
ORDER BY [TimeStamp] 

它返回最新的100條記錄,但我需要從第二臺這樣的替換Car_Id1Car_Id2的信息:Car_Id1 -> [Year + Make + Model]

回答

2

所以你需要什麼是二INNER JOIN s對VehicleSpecs表,每個Car_Id1Car_Id2一個。我把它們別名爲car1, car2

SELECT TOP 100 
    c.Id, 
    c.Slug, 
    c.TimeStamp, 
    /* Select the relevant columns from *both* of the joined tables */ 
    /* And give each column an alias to differentiate it from the other */ 
    car1.Year AS car1Year, 
    car1.Make AS car1Make, 
    car1.Model AS car1Model, 
    car2.Year AS car2Year, 
    car2.Make AS car2Make, 
    car2.Model AS car2Model 
FROM 
    Comparisons c 
    /* Join first against VehicleSpecs for Car_Id1 */ 
    INNER JOIN VehicleSpecs car1 ON c.Car_Id1 = car1.Id 
    /* Then once more for Car_Id2 */ 
    INNER JOIN VehicleSpecs car2 ON c.Car_Id2 = car2.Id 
ORDER BY c.TimeStamp 

你說你想要的最新,所以我想你實際上意味着對時間戳使用降序排列:

ORDER BY c.TimeStamp DESC 
+0

謝謝!有用。 –

1

加入對第二個表兩次:

select top 100 
    c.Id, c.Slug, c.TimeStamp, 
    s1.Year as Car1_Year, s1.Make as Car1_Make, s1.Model as Car1_Model, 
    s2.Year as Car2_Year, s2.Make as Car2_Make, s2.Model as Car2_Model 
from Comparsions c 
inner join VehicleSpecs s1 on s1.Id = c.Car_Id1 
inner join VehicleSpecs s2 on s2.Id = c.Car_Id2 
order by c.TimeStamp desc 

(注意:您可能需要將表格名稱更改爲Comparisons。)