代码之家  ›  专栏  ›  技术社区  ›  Brettski

Linq to SQL:左连接到MAX aggregate

  •  2
  • Brettski  · 技术社区  · 16 年前

    我正在尝试编写一个linqtosql语句,它显示所有客户记录,并且只显示发票表的匹配max(InvoiceId);基本上是客户的最新发票。需要左连接,因为客户可能没有任何发票,但需要在结果集中。

    外键为Customer.CustomerID=Invoice.CustomerID的两个基本表

    CREATE TABLE [dbo].[Customer](
        [CusomerId] [int] IDENTITY(1,1) NOT NULL,
        [CustomerName] [int] NOT NULL
        CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
    (
        [CustomerId] ASC
    )
    ) ON [PRIMARY]
    
    CREATE TABLE [dbo].[Invoice](
        [InvoiceId] [int] IDENTITY(1,1) NOT NULL,
        [CustomerId] [int] NOT NULL,
        [InvoiceTotal] [float] NOT NULL
        CONSTRAINT [PK_Invoice] PRIMARY KEY CLUSTERED 
    (
        [InvoiceId] ASC
    )
    ) ON [PRIMARY]
    

    所需结果集的SQL如下:

    SELECT *
    FROM Customers c
      LEFT JOIN 
        (Invoice i 
          INNER JOIN (SELECT CustomerId, MAX(InvoiceId) as InvId FROM Invoice GROUP BY CustomerId) as InvList 
          ON i.InvoiceNo = InvList.InvoiceNo) ON c.CustomerId = i.CustomerId
    

    2 回复  |  直到 16 年前
        1
  •  3
  •   Ben M    16 年前

    var query = 
        from c in ctx.Customer
        select new
        {
            Customer = c,
            LatestInvoice = ctx.Invoice
                .Where(i => i.CustomerId == c.CustomerId)
                .OrderByDescending(i => i.InvoiceId)
                .FirstOrDefault();
        };
    

    如果您想用另一种方法来实现,LINQ语法的可读性较差,但是 可以

    var latestInvoicesPerCustomerQuery = 
        from inv in ctx.Invoice
        group inv by inv.CustomerId into g
        select new { CustomerId = g.Key, InvoiceId = g.Max(inv => inv.InvoiceId) };
    
    var customersAndLatestInvoicesQuery = 
        from customer in ctx.Customer
        join linv in latestInvoicesPerCustomer 
             on customer.CustomerId equals linv.CustomerId
             into latestInvoiceJoin
        from latestInvoice in latestInvoiceJoin.DefaultIfEmpty() // left join
        join invoice in ctx.Invoice 
             on latestInvoice.InvoiceId equals invoice.InvoiceId
        select new
        {
            Customer = customer,
            LatestInvoice = invoice
        };
    

    第一个查询( latestInvoicesPerCustomerQuery )在对它或引用第一个查询的第二个查询进行枚举之前不会执行。就运行时而言,最后一个查询是一个表达式树——因此您可以认为第一个查询已被第二个查询吸收。

    如果您真的希望在一个查询中实现所有功能,也可以这样做:

    var customersAndLatestInvoicesQuery = 
        from customer in ctx.Customer
        join linv in (
                from inv in ctx.Invoice
                group inv by inv.CustomerId into g
                select new 
                { 
                    CustomerId = g.Key, 
                    InvoiceId = g.Max(inv => inv.InvoiceId) 
                }
            ) 
            on customer.CustomerId equals linv.CustomerId
            into latestInvoiceJoin
        from latestInvoice in latestInvoiceJoin.DefaultIfEmpty() // left join
        join invoice in ctx.Invoice 
             on latestInvoice.InvoiceId equals invoice.InvoiceId
        select new
        {
            Customer = customer,
            LatestInvoice = invoice
        };
    

    任何一种 customersAndLatestInvoicesQuery 应该大致翻译成你在文章中列出的SQL。

        2
  •  0
  •   Brettski    16 年前

    var latestInvoicesPerCustomerQuery = 
        from inv in ctx.Invoice
        group inv by inv.CustomerId into g
        join invj in ctx.Invoice on g.Max(inv => inv.InvoiceId) equals invj.InvoiceId
        select invj;
    
    var customersAndLatestInvoicesQuery = 
        from customer in ctx.Customer
        join linv in latestInvoicesPerCustomer 
             on customer.CustomerId equals linv.CustomerId
             into latestInvoiceJoin
        from latestInvoice in latestInvoiceJoin.DefaultIfEmpty() // left join
        select new
        {
            Customer = customer,
            LatestInvoice = invoice
        };
    

    在第一个语句中,我将invoice表连接回结果中,并故意不使用selectnew。

    //If I had done:
    select new {LatestInvoice=invj}
    // then I would have included the name LatestInvoice in the second statement:
    join linv in latestInvoicesPerCustomer 
                 on customer.CustomerId equals linv.LatestInvoice.CustomerId
                 into latestInvoiceJoin
    // Not desirable to me, and it seems it may be troublesome when used.
    

    我不知道为什么Ben M的解决方案不起作用,但我只在删除以下行时得到左连接产品:

    join invoice in ctx.Invoice 
             on latestInvoice.InvoiceId equals invoice.InvoiceId
    

    包括这条线的产品是一个内部连接。