我必须在MySQL中完成一项要求,我需要将常规表转换为另一个具有键值对的表,我无法找到任何答案(我对SQL来说相对较新)。 / p>
我已经能够找到与我的要求完全相反的方法的答案 - 这里是sample。
作为项目中数据库迁移活动的一部分,源表目前看起来像这样:
mysql> SELECT * FROM employee;
+------+-------+--------+
| id | fname | lname |
+------+-------+--------+
| 1 | Lex | Luthor |
| 2 | Clark | Kent |
| 3 | Lois | Lane |
+------+-------+--------+
3 rows in set (0.00 sec)
现在,必须将其转换为如下所示的表格:
+----------------+-----------------+
| attribute_name | attribute_value |
+----------------+-----------------+
| id | 1 |
| fname | Lex |
| lname | Luthor |
| id | 2 |
| fname | Clarke |
| lname | Kent |
| id | 3 |
| fname | Lois |
| lname | Lane |
+----------------+-----------------+
我已经尝试过,直到下面的查询,但结果还没有完成。
mysql> SELECT
-> T.COLUMN_NAME AS attribute_name,
-> CASE T.COLUMN_NAME
-> WHEN 'id' THEN employee.id
-> WHEN 'fname' THEN employee.fname
-> WHEN 'lname' THEN employee.lname
-> END AS attribute_value
-> FROM employee, INFORMATION_SCHEMA.COLUMNS T WHERE T.COLUMN_NAME IN
-> (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'data_migration_test_destination' AND TABLE_NAME = 'employee');
+----------------+-----------------+
| attribute_name | attribute_value |
+----------------+-----------------+
| ID | 1 |
| ID | 1 |
| id | 1 |
| fname | Lex |
| lname | Luthor |
| id | 1 |
| fname | Lex |
| lname | Luthor |
| id | 1 |
| ID | 2 |
| ID | 2 |
| id | 2 |
| fname | Clark |
| lname | Kent |
| id | 2 |
| fname | Clark |
| lname | Kent |
| id | 2 |
| ID | 3 |
| ID | 3 |
| id | 3 |
| fname | Lois |
| lname | Lane |
| id | 3 |
| fname | Lois |
| lname | Lane |
| id | 3 |
+----------------+-----------------+
27 rows in set (0.05 sec)
不确定为什么会在结果中弹出类似ID的内容,以及为什么其他键值对(id,fname和lname)会有多次重复。理想情况下,预期的行数必须为9,但我得到27!
答案 0 :(得分:1)
试试这个
mysql> CREATE TABLE #Test
(
[id] INT,
fname NVARCHAR(60),
lname NVARCHAR(60)
)
INSERT INTO #Test VALUES
(1, 'Lex', 'Luthor'),
(2, 'Clark', 'Kent'),
(3, 'Lois', 'Lane')
select * from #Test
select T2.N.value('local-name(.)', 'nvarchar(128)') as [Key],
T2.N.value('text()[1]', 'nvarchar(max)') as Value
from (select *
from #Test
for xml path(''), type) as T1(X)
cross apply T1.X.nodes('/*') as T2(N)
drop table #Test