SQL Server 2008 SELECT JOIN来自两个表

时间:2012-11-24 22:16:25

标签: sql sql-server sql-server-2008 select join

我有两张桌子,第一张是这样的:

[比较]

  • Id(int)
  • Car_Id1(int)
  • Car_Id2(int)
  • Slug(string)
  • 时间戳

第二个:

[VehicleSpecs]

  • Id(int)
  • 年(int)
  • Make(string)
  • 型号(字符串)

我有这个查询

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

它会返回最新的100条记录,但我需要将Car_Id1Car_Id2替换为第二个表中的信息,如下所示:Car_Id1 -> [Year + Make + Model]

2 个答案:

答案 0 :(得分:2)

因此,您需要的是针对INNER JOIN表的两个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

答案 1 :(得分: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。)