此查询需要一组评论,然后在tblCommentVotes表中统计他们的upvotes和downvotes。Linq可以优化这些子查询吗?
目前,它通过select子语句形式的select语句对这些进行计数。如果它在主要查询中处于某种组中,这会更有效吗?如果可以的话,任何人都可以告诉我如何做到这一点,因为我无法弄清楚如何做到这一点。
// Get comments
var q = (
from C in db.tblComments
where
C.CategoryID == Category &&
C.IdentifierID == Identifier
join A in db.tblForumAuthors on C.UserID equals A.Author_ID
orderby C.PostDate descending
select new
{
C,
A.Username,
UpVotes = (from V in db.tblCommentVotes where V.CommentID == C.ID && V.UpVote == true select new { V.ID }).Count(),
DownVotes = (from V in db.tblCommentVotes where V.CommentID == C.ID && V.UpVote == false select new { V.ID }).Count()
}
)
.Skip(ToSkip > 0 ? ToSkip : 0)
.Take(ToTake > 0 ? ToTake : int.MaxValue);
你是什么意思的“优化”?更高效的SQL?更少/更优雅的代码?如果SQL是你想要的,它可能有助于发布生成的SQL。 – Brook 2011-04-14 23:17:33
要优化SQL,请查看索引,而不是语言。那么,你确切的模式是什么? – 2011-04-14 23:45:29