gpt4 book ai didi

NHibernate - 联合三个 QueryOver

转载 作者:行者123 更新时间:2023-12-02 18:49:39 34 4
gpt4 key购买 nike

StackOverflow 用户您好,

我遇到了这个问题我有三个 QueryOver,每个都返回一个候选 id 列表,然后我用它来引入这些候选。为此我编写了以下代码。

        private IQueryOver<CandidateEntity, CandidateEntity> UnionPublicWithPrivateCandidates(
IQueryOver<CandidateEntity, CandidateEntity> publicCandidates,
IQueryOver<CandidateEntity, CandidateEntity> privateCandidate,
IQueryOver<CandidateEntity, CandidateEntity> candidatesByUserRole)
{
return ActiveCandidatesQueryOver.Where(Restrictions.Disjunction()
.Add(Subqueries
.WhereProperty<CandidateEntity>(c => c.Id)
.In((QueryOver<CandidateEntity>)publicCandidates.Select(c => c.Id)))
.Add(Subqueries
.WhereProperty<CandidateEntity>(c => c.Id)
.In((QueryOver<CandidateEntity>)privateCandidate.Select(c => c.Id)))
.Add(Subqueries
.WhereProperty<CandidateEntity>(c => c.Id)
.In((QueryOver<CandidateEntity>)candidatesByUserRole.Select(c => c.Id))));
}

这将返回正确的结果,生成的查询如下所示

SELECT *
FROM Applicants
WHERE IsActive = 1
and (Id in (SELECT Id from **FirstQueryOver**)
**or** Id in (SELECT Id from **SecondQueryOver**)
**or** Id in (SELECT Id from **ThirdQueryOver**))

问题是它使用了“or”。因此,查询速度非常慢。

如果我这样写:

SELECT *
FROM Applicants
WHERE IsActive = 1
and (Id in (SELECT Id from **FirstQueryOver**
union SELECT Id from **SecondQueryOver**
union SELECT Id from **ThirdQueryOver**))

它几乎立即完成。

您知道我应该如何重构代码以获得更好的性能吗?

谢谢你,阿德里安。

最佳答案

我进行了搜索,但没有找到任何内容,因此我进行了以下修改:

private IQueryOver<CandidateEntity, CandidateEntity> UnionPublicWithPrivateCandidates(
IQueryOver<CandidateEntity, CandidateEntity> publicCandidates,
IQueryOver<CandidateEntity, CandidateEntity> privateCandidate,
IQueryOver<CandidateEntity, CandidateEntity> candidatesByUserRole)
{
var excludedQueryCandidates = QueryOver
.WithSubquery.WhereNotExists(((QueryOver<CandidateEntity>)publicCandidates.Select(x => x.Id)))
.WithSubquery.WhereNotExists((QueryOver<CandidateEntity>)privateCandidate.Select(x => x.Id))
.WithSubquery.WhereNotExists((QueryOver<CandidateEntity>)candidatesByUserRole.Select(x => x.Id));

return QueryOver.WithSubquery.WhereNotExists((QueryOver<CandidateEntity>) excludedQueryCandidates.Select(Projections.Distinct(Projections.Id())));
}

这不是最好的解决方案,但应该可行。

关于NHibernate - 联合三个 QueryOver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12707379/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com