我正在使用Entity Framework来处理我的数据库,我需要帮助形成一个LINQ查询,它将帮助我获取列LoginId和AccNumber。我每个AccNumber只需要1个LoginId,对于哪个LoginId并不重要。就目前而言,大约有800K的LoginIds,只有~3000 AccNumber。
因此,最后我需要1个与1个LoginId关联的AccNumber。所以我应该有~3000行和2列。
以下是我需要加入的表格:
物品
ItemId,AccNumber,其他不相关的列
Block_Item
ItemId,BlockId,其他不相关的列
Bookversion_Block
BookversionId,BlockId,其他不相关的列
Sudent
LoginId,BookversionId,其他不相关的列
理想情况下,我想使用LINQ复制此SQL查询(只是尝试提供尽可能多的信息)
select max(StudentId) as StudentId, BookletVersionId into #ST from Student
group by BookletVersionId
select #ST.BookletVersionId, LoginId into #T1 from #ST
join Student ST on #ST.StudentId = ST.StudentId
select BookletVersionId, BlockId into #BVB from BookletVersion_Block
where
BookletVersionId in (select BookletVersionId from #ST)
select #T1.BookletVersionId, #BVB.BlockId, LoginId into #T2 from #T1
join BookletVersion_Block #BVB on #T1.BookletVersionId = #BVB.BookletVersionId
select max(BlockId) as BlockId, ItemId into #BI from Block_Item
where
BlockId in (select BlockId from #T2)
group by ItemId
select BookletVersionId, #T2.BlockId, ItemId, LoginId into #T3 from #T2
join #BI on #T2.BlockId = #BI.BlockId
select max(LoginId) as LoginId, AccessionNumber from #T3
join Item I on #T3.ItemId = I.ItemId
group by AccessionNumber order by LoginId
这是我尝试过的,然而,我得到的结果是不正确的,我回来了183,000条记录。显然,因为我的LINQ查询不正确,这就是我寻求帮助的原因。
var q = (from items in context.Items
join context.Block_Item
on items.ItemId equals bi.ItemId into bi
join context.BookletVersion_Block
on bi.Select(x => x.BlockId).FirstOrDefault() equals BVB.BlockId into BVB
join context.Students
on BVB.Select(x => x.BookletVersionId).FirstOrDefault() equals st.BookletVersionId into st
//'VH098334'
select new { LoginId = st.Select(x => x.LoginId).FirstOrDefault().ToString(), AccNum = items.AccessionNumber.ToString() });
答案 0 :(得分:2)
您可以在select语句中使用子查询和FirstOrDefault
来获取LoginId
var query =
from items in context.Items
select new
{
AccNum = items.AccessionNumber,
LoginId = (
from bi in context.Block_Item
join bb in context.BookletVersion_Block on bi.BlockId equals bb.BlockId
join st in context.Students on bb.BookversionId equals st.BookversionId
where items.ItemId == bi.ItemId
select st.LoginId
).FirstOrDefault()
};