1

我有两张桌子,第一张看起来像这样:

[比较]

  • 标识(整数)
  • Car_Id1 (int)
  • Car_Id2 (int)
  • 蛞蝓(串)
  • 时间戳

第二个:

[车辆规格]

  • 标识(整数)
  • 年份(整数)
  • 制作(字符串)
  • 型号(字符串)

我有这个查询

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

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

4

2 回答 2

2

所以你需要的是两个INNER JOINs 靠在VehicleSpecs桌子上,每个sCar_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
于 2012-11-24T22:19:18.263 回答
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。)

于 2012-11-24T22:21:12.500 回答