首页 > 解决方案 > 如何根据每一行的另一列的值将值插入一列?

问题描述

# table schema
CREATE TABLE `ref_str` (
  `ref_id` int(11) DEFAULT NULL,
  `ref_str` varchar(4096) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

这是当前数据:

+--------+--------------------+
| ref_id | ref_str            |
+--------+--------------------+
|   NULL | [5] www.NCCN.com   |
|   NULL | [4] www.nhc.gov.cn |
|   NULL | [14] www.hc.gov.cn |
|   NULL | [146] someh.gov.cn |
+--------+--------------------+

我想迭代地将同一行内的ref_idint 值插入列中。[]ref_str

结果应如下所示:

+--------+--------------------+
| ref_id | ref_str            |
+--------+--------------------+
|    5   | [5] www.NCCN.com   |
|    4   | [4] www.nhc.gov.cn |
|   14   | [14] www.hc.gov.cn |
|  146   | [146] someh.gov.cn |
+--------+--------------------+

我正在使用 MySQL 5.7.32。

谢谢。

标签: mysqlstored-procedures

解决方案


你可以SUBSTRING_INDEX在这里使用,例如:

SELECT
    SUBSTRING(SUBSTRING_INDEX(ref_str, ']', 1), 2) AS ref_id,
    ref_str
FROM ref_str;

下面演示链接的屏幕截图

演示


推荐阅读