如果我有一个像这样的表my_table
:
| id | val1 | val2|
| 1 | foo1 | bar |
| 2 | foo2 | baz |
| 3 | foo3 | bam |
我有一个硬编码的逗号分隔值列表,这些值是我通过编程生成的:spam, eggs, ham
。
我想将我的值插入列val1
中。我在想像这样的东西:
UPDATE my_table SET val1 = SELECT * FROM (VALUES ('spam'),('eggs'),('ham'))
但这给了我一个语法错误(MySQL 5.6.44)
最终结果应如下所示:
| id | val1 | val2|
| 1 | spam | bar |
| 2 | eggs | baz |
| 3 | ham | bam |
答案 0 :(得分:6)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,val1 VARCHAR(12) NOT NULL
,val2 VARCHAR(12) NOT NULL
);
INSERT INTO my_table VALUES
(1,'foo1','bar'),
(2,'foo2','baz'),
(3,'foo3','bam');
UPDATE my_table SET val1 = SUBSTRING_INDEX(SUBSTRING_INDEX('spam,eggs,ham',',',id),',',-1);
SELECT * FROM my_table;
+----+------+------+
| id | val1 | val2 |
+----+------+------+
| 1 | spam | bar |
| 2 | eggs | baz |
| 3 | ham | bam |
+----+------+------+
答案 1 :(得分:5)
@Strawberry 的answer确实是模范。但是如果id
的值不连续怎么办。
例如,id
的值为2, 5, 6
。在这种情况下,我们可以使用MariaDB 10.2 + / MySQL 8+中的Row_Number()
功能来模拟连续的new_id
。我还注意到,您输入的逗号分隔字符串在逗号后有空格。要处理此问题(可变的间距),我们可以在子字符串操作之后使用Trim()
函数。以excellent answer by @Strawberry为基础:
模式(MySQL v8.0)-View on DB Fiddle
CREATE TABLE your_table_name
(id INT UNSIGNED PRIMARY KEY
,val1 VARCHAR(12) NOT NULL
,val2 VARCHAR(12) NOT NULL
);
INSERT INTO your_table_name VALUES
(2,'foo1','bar'),
(5,'foo2','baz'),
(6,'foo3','bam');
更新查询
UPDATE your_table_name t1
JOIN (SELECT Row_number()
OVER (
ORDER BY id) AS new_id,
id
FROM your_table_name) t2
ON t2.id = t1.id
SET val1 =
Trim(Substring_index(Substring_index('spam, eggs, ham', ',', t2.new_id), ',', -1));
检查数据
SELECT * FROM your_table_name;
| id | val1 | val2 |
| --- | ---- | ---- |
| 2 | spam | bar |
| 5 | eggs | baz |
| 6 | ham | bam |
在旧版本的MySQL / MariaDB中,窗口功能不可用。在这种情况下,我们可以利用user-defined variables来模拟new_id
:
模式(MySQL v5.7)-View on DB Fiddle
CREATE TABLE your_table_name
(id INT UNSIGNED PRIMARY KEY
,val1 VARCHAR(12) NOT NULL
,val2 VARCHAR(12) NOT NULL
);
INSERT INTO your_table_name VALUES
(2,'foo1','bar'),
(5,'foo2','baz'),
(6,'foo3','bam');
更新查询
UPDATE your_table_name t1
JOIN (SELECT @rn := @rn + 1 AS new_id,
id
FROM your_table_name
CROSS JOIN (SELECT @rn := 0) vars
ORDER BY id) t2
ON t2.id = t1.id
SET val1 =
Trim(Substring_index(Substring_index('spam, eggs, ham', ',', t2.new_id), ',', -1));
检查数据
SELECT * FROM your_table_name;
| id | val1 | val2 |
| --- | ---- | ---- |
| 2 | spam | bar |
| 5 | eggs | baz |
| 6 | ham | bam |