我有点遇到这个问题:我有一个sqlite数据库,其中包含两个使用公共ID连接的表。我想从两个表中检索数据,并填充一个新表格,表示' table3'列有' category_id','问题',correct_answer',' wrong_answer1',wrong_answer2',' wrong_answer3'。如何实现这一目标?请看下面的图片。
提前多多感谢!
答案 0 :(得分:1)
假设您总是有一个正确答案和三个错误答案,您可以使用此查询:
SELECT Q.category_id,
Q.value AS Question,
RA.value AS CorrectAns,
WA1.value AS WrongAns1,
WA2.value AS WrongAns2,
WA3.value AS WrongAns3
FROM question Q
INNER JOIN answer RA ON (RA.question_id = Q.id AND RA.isCorrect = 1)
INNER JOIN answer WA1 ON (WA1.question_id = Q.id AND WA1.isCorrect = 0)
INNER JOIN answer WA2 ON (WA2.question_id = Q.id AND WA2.isCorrect = 0)
INNER JOIN answer WA3 ON (WA3.question_id = Q.id AND WA3.isCorrect = 0)
WHERE WA1.id < WA2.`id`
AND WA2.id < WA3.`id`
AND Q.id = 102752
如果错误答案的数量不总是三,您可以使用其他查询。
SELECT Q.category_id,
Q.value AS Question,
RA.value AS CorrectAns,
GROUP_CONCAT(WA.value) AS WrongAnswers
FROM question Q
INNER JOIN answer RA ON (RA.question_id = Q.id AND RA.isCorrect = 1)
LEFT JOIN answer WA ON (WA.question_id = Q.id AND WA.isCorrect = 0)
WHERE Q.id = 102752
请注意,在这种情况下,所有错误的答案都会在同一列中返回。