Linq左外连接到两个表

时间:2014-04-10 20:02:57

标签: c# linq

无论如何都在这个问题上停留了很长时间。

    SELECT
    [cr].[ItemID]
   ,[cr].[LatestEnteredDate]
   ,[cr].[LatestSentDate]
   ,[cr].[LatestReceivedDate]
   ,CASE WHEN LatestSentDate IS NULL
              OR ISNULL([LatestReceivedDate],'1900-01-01') < LatestEnteredDate THEN 1
         ELSE 0
    END AS Outstanding

   ,j.[JobNo]
   ,j.[VersionRef]
   ,j.[CardTitle]
   ,i.[BarcodeNo]
   ,i.[SerialNo]
   ,i.[BundleNo]
   ,i.[CartonNo]
   ,i.[PalletNo]
FROM
    (
     SELECT
        [cri].[ItemID]
                   --,[cri].[EnteredBy]
       ,MAX([cri].[EnteredDate]) AS LatestEnteredDate
       ,MAX([crr].[SentDate]) AS LatestSentDate
       ,MAX([crx].[ReceivedDate]) AS LatestReceivedDate
     FROM
        [dbo].[CardReissue] AS cri
     LEFT JOIN [dbo].[CardReissueRequests] AS crr ON [cri].[ItemID] = [crr].[ItemID]
     LEFT JOIN [dbo].[CardReissueReceipts] AS crx ON [cri].[ItemID] = [crx].[ItemID]
     GROUP BY
        [cri].[ItemID]
    ) cr
INNER JOIN [dbo].[Items] AS i ON i.ID = cr.[ItemID]
INNER JOIN [dbo].[Jobs] AS j ON [i].[JobID] = [j].[ID]

试图将其分解为步骤,因此决定从左连接开始到两个表(T1到T2和T1到T3)

SELECT
        [cri].[ItemID]
                   --,[cri].[EnteredBy]
       ,([cri].[EnteredDate]) 
       ,([crr].[SentDate]) 
       ,([crx].[ReceivedDate]) 
     FROM
        [dbo].[CardReissue] AS cri
     LEFT JOIN [dbo].[CardReissueRequests] AS crr ON [cri].[ItemID] = [crr].[ItemID]
     LEFT JOIN [dbo].[CardReissueReceipts] AS crx ON [cri].[ItemID] = [crx].[ItemID]

在LinqPd中已经达到了这个目的:

    var query =(
            from cr in CardReissues
            join crreq in CardReissueRequests
                on cr.ItemID equals crreq.ItemID into req
            join crrx in CardReissueReceipts
                on cr.ItemID equals crrx.ItemID
                orderby cr.EnteredDate
                from rx in req.DefaultIfEmpty()
            select new { 
            //cr.ItemID,
            rx.ItemID,
            cr.EnteredDate,
            rx.SentDate,
            crrx.ReceivedDate
        }
).ToList(); 

但是这给了我第一个表的内部联接:

SELECT [t2].[ItemID] AS [ItemID], [t0].[EnteredDate], [t2].[SentDate] AS [SentDate], [t1].[ReceivedDate]
FROM [CardReissue] AS [t0]
INNER JOIN [CardReissueReceipts] AS [t1] ON [t0].[ItemID] = [t1].[ItemID]
LEFT OUTER JOIN [CardReissueRequests] AS [t2] ON [t0].[ItemID] = [t2].[ItemID]
ORDER BY [t0].[EnteredDate]

有人能指出我正确的方向吗?

0 个答案:

没有答案