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

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

这可能吗?

最佳答案

您可以使用交叉连接技巧来“反透视”这些值:

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/

相关文章:

sql - 我怎样才能使这个 Ruby on Rails 页面更有效率?

php - 如何操作/访问从自动完成 ajax 收到的 json?

SQL:如何将两个表中的主键值插入主表

php - CakePHP 表关系 $belongsTo 在添加操作中的下拉菜单中不显示任何记录

php - MySQL更新行最高值加1

sql - 向 SQL 查询添加一个标志列,根据列值提取最新行

sql - 只有内置函数的 urlencode

mysql - mysql中覆盖索引是否比最左前缀索引策略优先级高?

mysql - 在MySQL中插入外语字符

php - 更改选项字段时新增查询数据库