你好,我的查询有点问题
questions
----------------------------------------------------------------------
| id | question_id | question |right_answer | question_type |
----------------------------------------------------------------------
| 1 | 500 | string | a | 1,2 |
| 2 | 600 | string | b | 1,2,3 |
| 3 | 620 | string | c | 3,1,2 |
| 4 | 750 | string | c | 4,1 |
| 5 | 800 | string | b | 5,1 |
| 6 | 900 | string | a | 1 |
----------------------------------------------------------------------
users_answers
--------------------------------------------------------
| id | question_id2 | user_id | question_true |
--------------------------------------------------------
| 1 | 500 | 2 | 1 |
| 2 | 500 | 1 | 1 |
| 3 | 600 | 2 | 1 |
| 4 | 600 | 1 | 1 |
| 5 | 900 | 1 | 1 |
| 6 | 800 | 2 | 1 |
--------------------------------------------------------
category
---------------------------------------------
| id | question_id3 | category_id |
---------------------------------------------
| 1 | 500 | 1 |
| 2 | 600 | 1 |
| 3 | 620 | 1 |
| 4 | 750 | 1 |
| 5 | 800 | 1 |
| 6 | 900 | 1 |
---------------------------------------------
SELECT category.*, questions.*, users_answers.* FROM category
LEFT JOIN questions ON category.question_id3 = questions.question_id
LEFT JOIN users_answers ON category.question_id3 = users_answers.question_id2
WHERE question_type LIKE '%1%' AND category_id = 1
order by case when user_id = '1' then 1 else 0 end, questions.id ASC
现在我变成了 8 个结果,但只有 6 个问题。我知道问题是加入。 id1,id2问题是double(两个答案)
最佳答案
在您的查询中,您会得到所有问题和任何相关的答案。如果某个特定问题没有答案,则 LEFT JOIN
中的所有 users_answers
字段都将为 NULL
值。因此,您可以将 users_answers
中的任何字段添加到您的 ORDER BY
:
ORDER BY question_true, users_answers.id -- Default sort is ASC
这应该首先返回没有答案的问题(NULL
值)。
关于mysql - 加入双录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172135/