mysql-动态选择行作为列

时间:2018-10-25 10:54:40

标签: mysql sql view dynamic-sql

更新:我想使用动态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_option表就像

+----+----------+-------------+-------+
| 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 |
+----+----------+-------------+-------+

0 个答案:

没有答案