mysql - 加入双录

标签 mysql sql

你好,我的查询有点问题

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(两个答案)

http://sqlfiddle.com/#!9/03b108/3

最佳答案

在您的查询中,您会得到所有问题和任何相关的答案。如果某个特定问题没有答案,则 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/

相关文章:

php - 从外部数据库中发现字符集

java - 连接到远程数据库的问题

php - 如何在 PHP 中安排 MySQL 数据库的定期更新?

php 和 MySQL 初学者接受用户输入、修改数据库并返回值

mysql - 在 Windows 7 中为 MySQL 安装 ODBC 数据源

php - 使用 html 表单更新 php 上的 sql 表

mysql - 在 MySQL 中高效获取前一条记录(通过索引)

sql - 判断一行数据是否已更改的简单方法是什么?

java - SQL:connection.close - 需要一些练习提示

mysql - 如何在某些表上使用左连接编写正确的 sql?