我需要将静态表中的数据插入到具有多个自定义选项的表中,因此如下所示。
一个表:
+------+------+--------+-------+
| name | type | weight | color |
+------+------+--------+-------+
| 1 | A | 10 | green |
+------+------+--------+-------+
| 2 | B | 3 | blue |
+------+------+--------+-------+
| 3 | D | 9 | gold |
+------+------+--------+-------+
期望的输出:
+------+-------------+--------------+
| name | option_name | option_value |
+------+-------------+--------------+
| 1 | type | A |
+------+-------------+--------------+
| 1 | weight | 10 |
+------+-------------+--------------+
| 1 | color | green |
+------+-------------+--------------+
| 2 | type | B |
+------+-------------+--------------+
| 2 | weight | 3 |
+------+-------------+--------------+
| 2 | color | blue |
+------+-------------+--------------+
| 3 | type | D |
+------+-------------+--------------+
| 3 | weight | 9 |
+------+-------------+--------------+
| 3 | color | gold |
+------+-------------+--------------+
这可能吗?
最佳答案
您可以使用交叉连接技巧来“反透视”这些值:
select
t.name,
case x.i
when 1 then 'type'
when 2 then 'weight'
when 3 then 'color'
end option_name,
case x.i
when 1 then type
when 2 then cast(weight as char(50))
when 3 then color
end option_value
from your_table t
cross join (
select 1 i union all
select 2 i union all
select 3 i
) x
cast(weight as char(50))
weight 是必需的,因为数据类型需要保持一致,weight(可能)是一个数字列,需要转换成字符串。
SQLFiddle
关于mysql - 从 A 表的一行中进行多项选择,并将结果作为多行插入 B 表中,并在一个查询中重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507979/