从A表中的一行中多次选择,并将结果作为B表中的多行插入,并在一个查询中重复

时间:2017-02-28 11:48:49

标签: mysql sql

我需要将静态表中的数据插入到具有多个自定义选项的表中,因此它看起来如下所示。

表格:

+------+------+--------+-------+
| 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         |
+------+-------------+--------------+

有可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用交叉连接技巧“UNPIVOT”值:

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)),因为数据类型需要一致且权重(可能)是一个数字列,需要转换为字符串。

SQLFiddle