[英]SQL Server 2008 SELECT JOIN from two tables
I have two tables, the first one looks like this: 我有两个表,第一个看起来像这样:
[Comparisons] [比较]
The second one: 第二个:
[VehicleSpecs] [VehicleSpecs]
I have this query 我有这个问题
SELECT TOP 100 *
FROM [Comparsions]
WHERE
ORDER BY [TimeStamp]
It returns the newest 100 records, but I need to replace the Car_Id1
and Car_Id2
with information from the second table like this: Car_Id1 -> [Year + Make + Model]
它返回最新的100条记录,但我需要用第二个表中的信息替换
Car_Id1
和Car_Id2
,如下所示: Car_Id1 -> [Year + Make + Model]
So what you'll need is two INNER JOIN
s against the VehicleSpecs
table, one for each Car_Id1
and Car_Id2
. 所以你需要的是针对
VehicleSpecs
表的两个INNER JOIN
,每个Car_Id1
和Car_Id2
。 I've aliased them as car1, car2
. 我把它们别名为
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
You said you wanted the newest , so I assume you actually mean to use descending order on the timestamps: 你说你想要最新的 ,所以我假设你实际上是指在时间戳上使用降序:
ORDER BY c.TimeStamp DESC
Join against the second table twice: 两次加入第二张桌子:
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
(Side note: You might want to correct the table name to Comparisons
.) (旁注:您可能希望将表名更正为
Comparisons
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.