Linq如何通过多重选择结果加入?

时间:2018-10-18 09:08:32

标签: asp.net-mvc linq linq-to-sql

问题:成员表中大约有600万条记录,加入表后通过contain('LIKE')搜索会变得非常慢

假设我有以下表格,

  

成员:id,成员名

     

member_scheme:member_scheme_id,member_id,scheme_id

     

方案:scheme_id,scheme_code

1-多-1

我想先在主表中按“ LIKE”搜索,然后将结果加入子表以达到scheme_code

如何在Linq中归档这样的SQL?

SELECT T2.code, * FROM (
    SELECT * FROM member as [Source1]
    WHERE [Source1].[member_name] LIKE '%TEST NAME%' ESCAPE N'~'
    ORDER BY [Source1].[id] DESC
    OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY
) T1
LEFT JOIN
(SELECT Source2.member_id, Source3.code FROM member_scheme as [Source2]
JOIN scheme as [Source3] ON Source3.scheme_id = Source2.scheme_id
) T2
ON T1.member_id = T2.member_id

我之前尝试过导航属性

    var memberRecords = db.Members.Select(mb => new ViewModel()
    {                
        MemberCode = mb.Code,
        SchemeCode = mb.MemberSchemes.FirstOrDefault().Scheme.Code,
    }).OrderByDescending(n => n.ID).AsQueryable();

memberRecords = memberRecords.Where(r => r.MemberCode.Contains("TEST NAME"));

并通过加入每行不匹配的结果(例如20-90秒)而变得非常慢。

所以我的想法是先过滤与“ LIKE”匹配的记录,我尝试通过仅用“ LIKE”搜索成员表,然后加入,只花了1-2秒即可返回结果,但是加入成员方案+方案表后最多需要20秒。

0 个答案:

没有答案