我有一个表格,其中包含有关项目和版本的详细信息,如下所示:
+--------+-----------+------------+----------------------------+
| BookId | VersionId | InstanceId | TitleText |
+--------+-----------+------------+----------------------------+
| 1 | 1 | 1 | A great book! |
| 1 | 2 | 2 | Great Book, v2! |
| 2 | 1 | 3 | Cooking for Dummies |
| 3 | 1 | 4 | Networks for Dummies |
| 2 | 2 | 5 | Cooking for Smarter People |
+--------+-----------+------------+----------------------------+
我试图查询BookId最新(最高)VersionId的所有行。所以我想要的结果集如下:
+--------+-----------+------------+----------------------------+
| BookId | VersionId | InstanceId | TitleText |
+--------+-----------+------------+----------------------------+
| 1 | 2 | 2 | Great Book, v2! |
| 3 | 1 | 4 | Networks for Dummies |
| 2 | 2 | 5 | Cooking for Smarter People |
+--------+-----------+------------+----------------------------+
我正在运行的SQL是:
select t1.* from Books t1
left outer join Books t2
on (t1.BookId = t2.BookId and t1.VersionId < t2.VersionId)
where t2.BookId is null
但是经过一些谷歌搜索后,我无法弄清楚如何将其转换为linq查询(使用扩展方法sytax)。我看到的例子往往会加入两个不同的表格,我只是没有弄清楚如何将其塑造成我需要的。
发现这一点,它似乎接近我正在寻找的东西,但我如何为Foo和Bar做同样的桌子呢?
Foo.GroupJoin(
Bar,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(x,y) => new { Foo = x, Bars = y })
.SelectMany(
x => x.Bars.DefaultIfEmpty(),
(x,y) => new { Foo=x.Foo, Bar=y});
答案 0 :(得分:3)
如何使用分组呢?
from x in myTable
group x by x.BookId into g
select g.OrderByDescending(y => y.VersionId).FirstOrDefault()
答案 1 :(得分:3)
一种方法是将您的反连接转换为where-not-exists:
select t1.*
from Books t1
where not exists (
select 1
from Books t2
where t2.BookId = t1.BookId and t2.VersionId > t1.VersionId
)
哪个应该转换为LINQ:
AllBooks.Where(t1 =>
!AllBooks.Any(t2 => t1.BookId == t2.BookId && t2.VersionId > t1.VersionId))
答案 2 :(得分:0)
在SQL中,我会将JOIN和GROUP BY结合起来找到每本书的最新版本:
span {
color: purple;
}
以下LINQ查询将由Entity Framework翻译成完全相同的内容:
<p>I will display <span>✔<span><p>