0

我只想从外部表中获取第一行。

我正在尝试执行类似于以下代码的操作,但出现错误。我无法获得 @rID =PartRequest.Id 。

 declare @rID int
 SELECT     
   @rID =PartRequest.Id
   , Products.Name AS ProductName
   , PartRequestPhotos.Id AS PartRequestPhotosId
   , PartRequest.IsInsuranceClaimed
 FROM PartRequest 
 INNER JOIN PartRequestStatus ON PartRequest.PartRequestStatusId = PartRequestStatus.Id 
 INNER JOIN UsersInfo ON PartRequest.UserId = UsersInfo.aspnet_UserId 
 INNER JOIN Products ON PartRequest.ProductId = Products.Id 
 LEFT OUTER JOIN PartRequestPhotos ON PartRequest.Id = 
      (select top 1 Id from  PartRequestPhotos where  PartRequestId =  @rID)
4

2 回答 2

0

我只想从外部表中获取第一行。

将其包含在子查询中,而不是JOIN像这样在条件中进行比较

...
LEFT OUTER JOIN
(
   select top 1 Id from  PartRequestPhotos where  PartRequestId =  @rID
)   PartRequestPhotos ON PartRequest.Id = PartRequestPhotos.Id
...
于 2012-11-11T13:28:12.300 回答
0

您无法获取@rID,因为在呈现数据之前执行了左连接,为了做到这一点,您需要将查询更改为以下内容:

只分配一个变量是不正确的,您要么将所有列分配给变量,要么不分配。

您需要使用外部应用,以便能够为左侧表的每一行调用子查询。

您需要指定 desc 或 asc,如果您输入 asc,它将为您获取第一个 id,desc 它将返回最新的。

        SELECT     
             PartRequest.Id
           , Products.Name AS ProductName
           , PartRequestPhotos.Id AS PartRequestPhotosId
           , PartRequest.IsInsuranceClaimed
         FROM PartRequest 
         INNER JOIN PartRequestStatus ON PartRequest.PartRequestStatusId = PartRequestStatus.Id 
         INNER JOIN UsersInfo ON PartRequest.UserId = UsersInfo.aspnet_UserId 
         INNER JOIN Products ON PartRequest.ProductId = Products.Id 
         OUTER APPLY
            (
              SELECT TOP 1 
                 Id
              FROM 
                 PartRequestPhotos
              WHERE 
                 PartRequestPhotos.PartRequestId = PartRequest.Id
              ORDER BY
                Id ASC
            ) PartRequestPhotos 
于 2012-11-11T15:16:51.293 回答