I have a design where we store answers to scripts s questions by given users. One script can have many questions and each question can be answered multiple times by a given user.
管理系统表(删除额外细节)大致如下:
-Scripts
ScriptId int (PK, identity)
-ScriptQuestions
ScriptId int (PK)
QuestionId int (PK)
-Questions
QuestionId int (PK, identity)
QuestionText varchar
-Answers
AnswerId int (PK, identity)
QuestionId int
UserId int
AnswerText varchar
I would like to query this database for a given script and a given user and obtain all questions and the last answer provided for each question (if any). In T-SQL I would do something like this:
SELECT
sq.QuestionId,
q.QuestionText,
la.AnswerText
FROM
ScriptQuestions sq
ON s.ScriptId = sq.ScriptId
INNER JOIN Questions q
ON sq.QuestionId = q.QuestionId
LEFT OUTER JOIN (
SELECT
QuestionId,
AnswerText
FROM Answers
WHERE AnswerId IN (
SELECT
MAX(AnswerId) LastAnswerId
FROM Answers
WHERE UserId = @userId
GROUP BY QuestionId
)
) la
ON q.QuestionId = la.QuestionId
WHERE
sq.ScriptId = @scriptId
(未经过测试,但我认为它接近我将做的事情)
我正在使用Linq ToEF进行3号MVC申请,并利用这些结果:
var questions = from sq in script.ScriptQuestions
select new QuestionsAnswers
{
QuestionId = sq.QuestionId,
QuestionText = sq.Question.QuestionText,
LastAnswer = sq.Question.Answers
.Where(a => a.UserId == userId)
.OrderByDescending(a => a.AnswerId)
.Select(a => a.AnswerText)
.FirstOrDefault()
};
当我从VS 2010接任英特尔利特人简介会时,我确实取得了同样的结果。 我可以看到,林克将这段话翻译成发送了SlectT
。 因此,如果文字有20个问题,就会问数据库至少40次,而不是像上文那样只发送一份内容说明。
我试图改变我的发言方式,但我未能克服<条码>SlectT发言问题。
这不能是正确的方式,也不能是?