假设我有一个只有1行的SQL表:
+----+----+----+------+------+------+-------+
| U1 | U2 | U3 | ACC1 | ACC2 | ACC3 | TOTAL |
+----+----+----+------+------+------+-------+
| 1 | 2 | 4 | 10 | 18 | 17 | 45 |
+----+----+----+------+------+------+-------+
上表包含以下字段:
现在,我想通过将此表转换为以下形式来使该表更具可读性。
+----+----+
| U | ACC|
+----+----+
| 1 | 10 |
| 2 | 18 |
| 4 | 17 |
+----+----+
我如何在MySQL中执行此操作? PIVOT / UNPIVOT有帮助吗?如果是这样,怎么样?
答案 0 :(得分:4)
最简单的方法是union all
:
select u1 as u, acc1 as acc from t
union all
select u2 as u, acc2 as acc from t
union all
select u3 as u, acc3 as acc from t;
这需要扫描表三次。对于一行,在性能方面完全没有区别。
pivot
/ unpivot
无济于事,因为MySQL不支持它。