填写mysql中重复序列的空白

时间:2016-07-11 01:21:19

标签: mysql sql

我有一个表格,用于存储问题1 - 16以及用户给出的答案,并按其唯一ID进行分组。例如:

+--------+-----------------+--------+
| number | question_number | answer |
+--------+-----------------+--------+
| 1      | 1               | y      |
+--------+-----------------+--------+
| 1      | 2               | n      |
+--------+-----------------+--------+
| 1      | 3               | y      |
+--------+-----------------+--------+
| 2      | 1               | n      |
+--------+-----------------+--------+
| 2      | 3               | y      |
+--------+-----------------+--------+

我想要的是SELECT或INSERT,它将填充序列中的缺失值。因此,在“数字”2的情况下,它将填充question_number 2并为回答插入空值。所以基本上我想填补重复序列的空白(在我的例子中,1-3)

1 个答案:

答案 0 :(得分:1)

您可以使用cross joinleft join

执行此操作
select n.number, qn.question_number, q.answer
from (select distinct number from questions) n cross join
     (select distinct question_number from questions) qn left join
     questions q
     on q.number = n.number and q.question_number = qn.question_number;