使用MySQL重塑数据

时间:2014-02-04 23:10:54

标签: mysql pivot

我有一个像这样构建的表:

+----+---------+---------+----+----+
| id | filter1 | filter2 | q1 | q2 |
+----+---------+---------+----+----+
|  1 | america | y       |  1 |  2 |
|  2 | asia    | y       |  4 |  3 |
+----+---------+---------+----+----+

我需要的是在同一标题question下的q1和q2上旋转(?),以及名为answers的新列中的行数据

决赛桌如下:

+----+---------+---------+----------+--------+
| id | filter1 | filter2 | question | answer |
+----+---------+---------+----------+--------+
|  1 | america | y       | q1       |      1 |
|  1 | america | y       | q2       |      2 |
|  2 | asia    | y       | q1       |      4 |
|  2 | asia    | y       | q2       |      3 |
+----+---------+---------+----------+--------+

1 个答案:

答案 0 :(得分:1)

最简单的方法是union all

select id, filter1, filter2, 'q1' as question, q1 as answer
from table t
union all
select id, filter1, filter2, 'q2' as question, q2 as answer
from table t;

如果您有大型表或更多问题,那么这可能不是最有效的方法。

编辑:

对于一张大桌子,这可能更有效:

select id, filter1, filter2,
       (case when n.n = 1 then 'q1' else 'q2' end) as question,
       (case when n.n = 1 then q1 else q2 end) as answer
from table t cross join
     (select 1 as n union all select 2 as n) n;

对于union all中的每个子查询,这应该只对表进行一次全表扫描,而不是一次。