此查詢需要一組評論,然後在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