mysql-dynamic选择行作为列

llew8vvj  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(138)

更新:我想使用动态sql选择问题作为列,并将答案放在行中,如游标或循环,这是可能的吗?
我想要这样的选择结果

+--------+---------------+--------------------------------------------------------------------------+
| userid | Living Status | This is another question get from row and it's longer than 64 characters |
+--------+---------------+--------------------------------------------------------------------------+
|     19 | married       | q2_opt3                                                                  |
+--------+---------------+--------------------------------------------------------------------------+

这是我的问题

select 
       userid,
        min(if(question.ordering=1,o.name,NULL )) as 'Living Status',
        min(if(question.ordering=2,o.name,NULL )) as 'This is another question get from row and it's longer than 64 characters'
from answer
       inner join question on question.key_value = answer.key_value
       inner join q_option o on question.id = o.question_id and o.value = answer.answer
where userid in (19)
GROUP BY id

问题表就像

+----+----------+---------------------------------------------------------------------------+--------------+
| id | ordering |                                 question                                  |  key_value   |
+----+----------+---------------------------------------------------------------------------+--------------+
|  1 |        1 | Living Status                                                             | livingStatus |
|  2 |        2 | This is another question get from row and it's longer than 64 characters  | question_2   |
+----+----------+---------------------------------------------------------------------------+--------------+

答案表就像

+----+--------+--------------+--------+
| id | answer |  key_value   | userid |
+----+--------+--------------+--------+
|  1 |      2 | livingStatus |     19 |
|  2 |      3 | question_2   |     19 |
+----+--------+--------------+--------+

q\u选项表如下

+----+----------+-------------+-------+
| id |   name   | question_id | value |
+----+----------+-------------+-------+
|  1 | single   |           1 |     1 |
|  2 | married  |           1 |     2 |
|  3 | divorced |           1 |     3 |
|  4 | q2_opt1  |           2 |     1 |
|  5 | q2_opt2  |           2 |     2 |
|  6 | q2_opt3  |           2 |     3 |
+----+----------+-------------+-------+

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题