1

我要翻译的查询是:

SELECT 
    MIN(BookCopies.id) as id, Books.title, Authors.name, Publishers.name
FROM 
    dbo.BookCopies
INNER JOIN 
    Books ON BookCopies.bookId = Books.id
INNER JOIN 
    Authors ON Books.authorId = Authors.id
INNER JOIN 
    Publishers ON BookCopies.publisherId = Publishers.id
WHERE 
    BookCopies.sold = 0 
GROUP BY 
    Books.title, Authors.name, Publishers.name;

我试图解决这个问题 3 个小时,但我不能......:/

Linq 代码:

var query = (from bc in db.BookCopies
            join b in db.Books on bc.bookId equals b.id
            join a in db.Authors on b.authorId equals a.id
            join p in db.Publishers on bc.publisherId equals p.id
            where (bc.sold == false && bc.price != null && bc.price != 0)
            group bc by new {b.title, author = a.name, publisher = p.name} into gr
            select new {gr.Key.title, gr.Key.author, gr.Key.publisher});

但这是不正确的。

4

1 回答 1

2

这里的技巧是选择加入中间数据类型(行)的结果,稍后将对其进行分组:

from bc in db.BookCopies
join b in db.Books on bc.bookId equals b.id
join a in db.Authors on b.authorId equals a.id
join p in db.Publishers on bc.publisherId equals p.id
where bc.sold == 0
select new { bc.id, b.title, author = a.name, publisher = p.name } into row
group row by new { row.title, row.author, row.publisher } into g
select new {
   id = g.Min(x => x.id),
   g.Key.title,
   g.Key.author,
   g.Key.publisher
}

这会产生您正在寻找的完全相同的查询。

于 2013-09-26T10:33:33.840 回答