我的ms sql中有这种查询。
SELECT
OdeaMainDataBase.dbo.ItemChoicesTable.*,
CASE
WHEN EXISTS(SELECT * FROM StudentTestTablefromRemark
WHERE StudID = @studId AND ExamID = @examId
AND ItemBankID = @itemBankId
AND ChoiceID = OdeaMainDataBase.dbo.ItemChoicesTable.ChoiceID)
THEN 'True'
ELSE 'False'
END AS isAnswered
FROM
OdeaMainDataBase.dbo.ItemChoicesTable
WHERE
ItemBankID = @itemBankId
我观察到我所做的CASE
语句导致我的查询运行缓慢。当我删除CASE
时,它运行得很快,但我的输出需要这种情况。
这是我想要显示的结构
项目选择表
ItemBankID ChoiceID ChoiceLetter
--------------------------------------
1 1 A
1 2 B
1 3 C
2 4 A
2 5 B
2 6 C
学生答案表
ItemBankID ChoiceID ChoiceLetter StudentId
-------------------------------------------------
1 2 B 123
2 6 C 123
所需输出
ItemBankID ChoiceID ChoiceLetter IsAnswered
----------------------------------------------------
1 1 A False
1 2 B True
1 3 C False
2 4 A False
2 5 B False
2 6 C True
我希望在不减慢程序速度的情况下实现输出。
任何想法都会对我有用。
非常感谢
答案 0 :(得分:2)
试试这个
SELECT i.*,
CASE
WHEN s.ChoiceID IS NULL THEN 'False'
ELSE 'True'
END
FROM OdeaMainDataBase.dbo.ItemChoicesTable i
LEFT OUTER JOIN StudentTestTablefromRemark s
ON s.ChoiceID = i.ChoiceID
AND s.ItemBankID = i.ItemBankID
AND s.StudID = @studId
AND s.ExamID = @examId
WHERE i.ItemBankID = @itemBankId
答案 1 :(得分:1)
尝试此查询
SELECT OdeaMainDataBase.dbo.ItemChoicesTable.*,
ISNULL(a,'False') as isAnswered
FROM OdeaMainDataBase.dbo.ItemChoicesTable
left outer join(Select 'True' as a,ChoiceID FROM StudentTestTablefromRemark
Where StudID=@studId AND ExamID=@examId AND ItemBankID=@itemBankId )b on b.ChoiceID=OdeaMainDataBase.dbo.ItemChoicesTable.ChoiceID
Where ItemBankID = @itemBankId