查询优化。获取具有最大列值的行

时间:2014-05-15 08:12:29

标签: sql linq

是否可以更好地优化此linq查询:

var query = Context.books.Where(book=> book.Author == "Murakami"
                                        && book.Year = 2004
                                        && book.price ==
                                        Context.books.Where(book => book.Author == Murakami")
                                        .Max(c => c.price));

我对Max部分感兴趣,因为作者与上面的内容相同

1 个答案:

答案 0 :(得分:1)

如果你想要2004年村上最贵的书

这将检索0或1本书。

var mostExpensiveBook = Context.books.Where(book => book.Author = "Murakami" &&
                                        book.Year == 2004)
                         .OrderByDescending(m => m.price)
                         .FirstOrDefault();

如果你想要Murakami 2004的所有书籍,其价格相当于最昂贵的村上书,你可以将你的查询重写为(相当于你的查询,只是避免重复“Murakami”并使用let关键字)。 / p>

这将检索0-n书。

var books = context.Books.Where(m => m.Author == "Murakami");

var mostExpensiveBooks = from book in books 
                         let mostExpensivePrice = books.Max(x => x.price)
                         where book.price == mostExpensivePrice &&
                               book.Year == 2004
                         select book;