转置mysql键值表

时间:2012-03-11 20:12:02

标签: mysql

我有一张这样的表:

+------+---------+-------------+------+ 
| id   | key     | value       | user | 
+------+---------+-------------+------+ 
|    1 | first   | foo         | 32   | 
|    2 | second  | bar         | 32   | 
|    3 | system  | more        | 32   | 
|    4 | first   | galaxy      | 21   | 
|    5 | second  | foo         | 45   | 
|    6 | system  | other       | 45   | 
+------+---------+-------------+------+ 

我需要将其转换为:

+-----------+------------+---------+------+ 
| first     | second     | system  | user |
+-----------+------------+---------+------+ 
|   foo     | bar        | more    | 32   |
|   galaxy  | NULL       | NULL    | 21   |
|   NULL    | foo        | other   | 45   | 
+-----------+------------+---------+------+ 

未使用ID, key 列将以列的形式转换,结果将按用户分组,非现有值将设置为NULL。这可能吗?

编辑:我忘了说 key 参数是动态的,事先不知道。

1 个答案:

答案 0 :(得分:0)

尝试此查询:

INSERT INTO transposed_table (first, second, system, user)
SELECT t1.value, t2.value, t3.value, t1.user
FROM initial_table as t1
OUTER_JOIN initial_table as t2 ON t2.user = t1.user
OUTER_JOIN initial_table as t3 ON t3.user = t2.user;

我将transposed_table新目标表格initial_table称为您已有的表格。