2012-03-11 70 views
0

我有一個這樣的表:移調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,關鍵列將在colums中進行轉換,結果將按用戶分組,並且不存在的值將被設置爲NULL。那可能嗎?

編輯:我忘了說參數是動態的,事先不知道。

回答

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你已經有一個。

+0

此查詢的問題是您應該提前知道密鑰。密鑰的編號和名稱未知 – Ivan 2012-03-11 23:00:30