从外表获得前1行

时间:2012-11-11 13:22:24

标签: sql sql-server

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

我正在尝试执行类似下面的代码,但收到错误。我无法得到@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)

2 个答案:

答案 0 :(得分:0)

  

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

将其包含在子查询中,而不是像JOIN那样比较它

...
LEFT OUTER JOIN
(
   select top 1 Id from  PartRequestPhotos where  PartRequestId =  @rID
)   PartRequestPhotos ON PartRequest.Id = PartRequestPhotos.Id
...

答案 1 :(得分:0)

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

仅分配一个变量是不正确的,您可以将所有列分配给变量,也可以不赋予变量。

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

按顺序你需要指定desc或asc,如果你输入asc它会得到你的第一个id,desc它将返回最新的id。

        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