如果答案为假,则选择正确的奇数

时间:2019-01-23 13:42:25

标签: mysql sql

我的数据库中有3个表,分别为:questionsanswerquestionodds

第一个(问题)有问题列表

+=========================+
|   ID   |    question    | 
+=========================+
|   1    |    Bla Bla     |
|   2    |    question    |
|   3    | Other Question |
+-------------------------+

第二个问题(AnswerQuestion)回答了特定问题的用户

+==================================================+
|   ID   | idQuestion | idOdd | idUser | isCorrect |
+==================================================+
|   1    |    4       |     2 |     5  |     0     |
|   2    |    3       |     1 |     1  |     1     |
|   3    |    1       |     3 |     10 |     0     |
+--------------------------------------------------+

第三个(赔率)的问题赔率与正确的赔率

+============================================+
|   ID   |    odd   | idQuestion | isCorrect |
+============================================+
|   1    |    One   |          1 |     0     |
|   2    |    Two   |          1 |     1     |
|   3    |   Three  |          1 |     0     |
+--------------------------------------------+

因此,要获取特定用户的答案,我使用此查询:

SELECT * FROM answerquestion a, question q, odds o
WHERE a.IdUser = :id AND a.IdOdd = o.ID AND a.IdQuestion = q.ID

工作正常,但是如果用户的回答为假,我想获得正确的奇数 为此,我在SQL上使用了IF语句,查询为:

SET SQL_BIG_SELECTS=1;
SELECT DISTINCT IF(o.isCorrect = 0, o.Corr.TheCorr, o.odd), q.Question
FROM answerquestion a, odds o, question q,
  ( SELECT o.odd AS TheCorr FROM odds o, question q WHERE o.isCorrect = 1 AND o.IdQuestion = q.ID) AS Corr
WHERE a.IdUser = 5
AND q.ID = a.idQuestion
AND a.IdOdd = o.ID

此查询的问题是答案为假,它为我提供了所有问题的所有正确答案并重复了问题

示例:

Question ID 4 'Bla Bla' | Correct odd of Question ID 1
Question ID 4 'Bla Bla' | Correct odd of Question ID 2
Question ID 4 'Bla Bla' | Correct odd of Question ID 3
Question ID 4 'Bla Bla' | Correct odd of Question ID 4
Question ID 4 'Bla Bla' | Correct odd of Question ID 5

我想要第4个问题的答案,我需要得到正确的赔率

Question ID 4 'Bla Bla' | Correct odd of Question ID 4

有帮助吗?

1 个答案:

答案 0 :(得分:1)

需要使用正确的JOIN。不确定应该选择哪些列,但是很容易解决。

SELECT q.id, q.question, o.odd as correct, o2.odd as user_odd
FROM question q
JOIN AnswerQuestion a ON a.idQuestion = q.id
JOIN Odds o ON o.questionID = q.id AND o.isCorrect = 1
JOIN Odds o2 ON o2.id = a.idOdd
WHERE a.idUser = 5