2012-11-11 78 views
0

我想只從外表獲得第一行。從外表獲取頂部1行

我想做下面的代碼,但得到一個錯誤。我無法獲取@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

你的代碼有什麼問題? – codingbiz

+0

我無法從PartRequest.Id獲取@rID(@rID = PartRequest.Id) – Eyal

回答

0

我想獲得僅從外部表的第一行。

其封裝在一個子查詢,而不是它在JOIN條件相比較,像這樣

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

我無法獲取@rID = PartRequest.Id,這會導致錯誤。 – Eyal

0

你不能得到@rID,因爲左連接數據的呈現之前執行,以這樣做你需要改變查詢以下內容:

只分配一個變量是不正確的,你可以將所有列分配給變量或不分配變量。

您需要使用outer apply才能夠爲左側表格的每一行調用子查詢。

按順序,你需要指定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