MySQL-创建新行并插入具有新ID的现有数据?

时间:2019-08-21 00:12:20

标签: mysql

我有一个类似于以下内容的MySQL表,是否可以:

1)复制与“类型= 42”相邻的现有“值” 2)在每条记录的末尾插入一个新行(追加) 3)将在“类型= 42”中找到的值添加到新行,但是将类型从42更改为“ 206”?如下所示,之前和之后。

这可能吗?

之前:

+-------+------+-------+---------+---------+
|  id   | name | abbr  | type    | value   |
+-------+------+-------+---------+---------+
|  123  | HCT  | HCT   | 42      | XYZ     |
|       |      |       | 57      | ABC     |
|       |      |       | 131     | RST     |
|       |      |       | 208     | 110     |
|  358  | CBC  | CBC   | 42      | 9AB     |
|       |      |       | 32      | GHI     |
|       |      |       | 11      | SB1     |
|       |      |       | 22      | LLY     |
|       |      |       | 57      | JKL     |
|       |      |       | 131     | 32B     |
|       |      |       | 263     | POF     |
|  102  | BMP  | BMP   | 42      | 444     |
|       |      |       | 131     | 09N     |
|       |      |       | 263     | 77M     |
|       |      |       | 35      | XJJ     |
|       |      |       | 11      | X10     |
|       |      |       | 22      | PLP     |
+-------+------+-------+---------+---------+

之后:

+-------+------+-------+---------+---------+
|  id   | name | abbr  | id_type | id_base |
+-------+------+-------+---------+---------+
|  123  | HCT  | HCT   | 42      | XYZ     |
|       |      |       | 57      | ABC     |
|       |      |       | 131     | RST     |
|       |      |       | 208     | 110     |
|       |      |       | 206     | XYZ     |
|  358  | CBC  | CBC   | 42      | 9AB     |
|       |      |       | 32      | GHI     |
|       |      |       | 11      | SB1     |
|       |      |       | 22      | LLY     |
|       |      |       | 57      | JKL     |
|       |      |       | 131     | 32B     |
|       |      |       | 263     | POF     |
|       |      |       | 206     | 9AB     |
|  102  | BMP  | BMP   | 42      | 444     |
|       |      |       | 131     | 09N     |
|       |      |       | 263     | 77M     |
|       |      |       | 35      | XJJ     |
|       |      |       | 11      | X10     |
|       |      |       | 22      | PLP     |
|       |      |       | 206     | 444     |
+-------+------+-------+---------+---------+

谢谢您的帮助!

我是MySQL的新手。

1 个答案:

答案 0 :(得分:0)

您应该可以使用INSERT ... SELECT查询来做到这一点:

INSERT INTO table1
SELECT id, name, abbr, 206, value
FROM table1
WHERE type = 42

请注意,我假设您要复制带有id的行中的nameabbrtype=42值。如果您希望它们为空白(如示例数据中一样),请将查询更改为

INSERT INTO table1
SELECT '', '', '', 206, value
FROM table1
WHERE type = 42

Demo on dbfiddle