您将如何转置此表:
旧表
+----+--------+-------------+-------------------+
| id | type | field | value |
+----+--------+-------------+-------------------+
| 1 | person | gender | female |
+----+--------+-------------+-------------------+
| 1 | person | age | 22 |
+----+--------+-------------+-------------------+
| 1 | person | name | Julie Smith |
+----+--------+-------------+-------------------+
| 1 | person | picture_url | www.pic.com/1.jpg |
+----+--------+-------------+-------------------+
| 2 | person | gender | male |
+----+--------+-------------+-------------------+
| 2 | person | name | Johnny Parsons |
+----+--------+-------------+-------------------+
像这样的表:
新表
+----+----------------+--------+------+-------------------+
| id | name | gender | age | picture_url |
+----+----------------+--------+------+-------------------+
| 1 | Julie Smith | female | 22 | www.pic.com/1.jpg |
+----+----------------+--------+------+-------------------+
| 2 | Johnny Parsons | male | Null | Null |
+----+----------------+--------+------+-------------------+
我们可以执行这样的查询:
INSERT INTO new_table SELECT
id::id as id,
max(case when field='name' then value else null end) as name,
max(case when field='gender' then value else null end) as gender,
max(case when field='age' then value else null end) as age,
max(case when field='picture_url' then value else null end) as picture_url
FROM old_table
WHERE 1=1
AND type = 'person'
GROUP BY
id
;
不幸的是,这个查询不可推广,如果我要添加新字段,那么这些字段将不会添加到新表中。有没有办法编写更通用的查询?
最佳答案
PIVOT
(PostgreSQL 中的CROSSTAB
)可能是您想要使用的。您正在有效地模拟查询中的 PIVOT
。但是,为此您需要了解您拥有的所有属性/列。
如果您事先不知道这些值,则可以以编程方式构造此类 SQL(在客户端中,或某些数据库允许执行生成的字符串)
关于mysql - 如何在 SQL 中以通用的方式转置表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41068003/