在匹配ID上加入两个表?

时间:2014-11-18 10:06:35

标签: sql-server

问题

我有一个查询,并希望根据匹配的ID

加入另一个表中的一列

到目前为止查询

SELECT DENumber, AcquiredDate, ItemDescription, ItemName, LocationID FROM dbo.Assets JOIN LocationName FROM dbo.Locations on ProductID             
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 6

两个表中的匹配ID为LocationID

问题

我的查询错误并抛出错误

Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'FROM'.

2 个答案:

答案 0 :(得分:3)

将您的查询重写为:

SELECT DENumber, AcquiredDate, ItemDescription, ItemName, LocationName
FROM dbo.Assets INNER JOIN dbo.Locations ON Assets.LocationId = Locations.LocationId            
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 6

澄清:在JOIN中,您必须在JOIN关键字的任意一侧指定两个表的名称。然后,在ON关键字后指定加入条件:

FROM <<table1>> INNER JOIN <<table2>> ON <<join criteria>>

在这里,我们只想要存在于两个表中的记录,这就是我们使用INNER连接的原因,但您也可以从LEFT表,RIGHT表或BOTH表中获取所有记录。在这种情况下,您将分别LEFT JOINRIGHT JOIN我们的OUTER JOIN

答案 1 :(得分:0)

SELECT L.DENumber, A.AcquiredDate, A.ItemDescription, A.ItemName, L.LocationID
 FROM dbo.Assets A JOIN 
  ON dbo.Locations L on 
 L.ProductID  = A.ProductID        
WHERE DATEDIFF(YEAR, A.AcquiredDate, GetDate()) >= 6