如何将 SELECT 子查询返回多行的表插入 INSERT INTO?

如何将 SELECT 子查询返回多行的表插入 INSERT INTO?

  INSERT INTO Results
(
People,
names,
)
VALUES
(
(
SELECT d.id
FROM Names f
JOIN People d ON d.id  = f.id
),


(
"Henry"
),
);

使用从该子查询返回的所有结果填充新表。没有 ERROR1242(21000) : 子查询返回多于1行我该怎么做

133601 次浏览
  INSERT INTO Results
(
People,
names,
)
SELECT d.id, 'Henry'
FROM Names f
JOIN People d ON d.id  = f.id
INSERT INTO Results (People, names )
SELECT d.id, 'Henry'
FROM Names f
JOIN People d ON d.id  = f.id

将静态字符串 HenrySELECT查询组合在一起。

INSERT INTO Results
(
People,
names,
)
VALUES
(
(
SELECT d.id
FROM Names f
JOIN People d ON (d.id  = f.id) limit 1
),


(
"Henry"
),
);

以下是我发现的有效方法。它有点长,但是需要多次处理额外的数据。

使用值从 table2向 table1插入多行。 例子:

INSERT INTO table1 (col1, col2, col3, col4, col5)
SELECT col1,col2,col3,col4,col5
FROM table2 t2
WHERE t2.val2 IN (MULTIPLE VALUES)
AND (Another Conditional);

您可以插入硬编码的值来插入具有重复数据的多行:

INSERT INTO table1 (col1, col2, col3, col4, col5)
SELECT "Value", col2, col3, "1900-01-01","9999-12-31"
FROM table2 t2
WHERE t2.val2 IN (MULTIPLE VALUES)
AND (Another Conditional);

注意: “ Value”、“1900-01-01”、“9999-12-31”将在插入的所有行中重复。

插入 ec _ element (Parentid,name)从 ec _ element 中选择 elementid,‘ STARTUP’,其中 name = ‘ BG’;

Insert 语句从满足条件和标签字符串的表中获取值 elementid。

这个错误(Subquery 返回多于1行)的原因是您使用了括号 ()。仔细寻找最佳答案。它不包含子查询周围的括号

在 MySql 中,可以像下面这样插入来自字符串的多个值,以避免重复。

   insert into brand(name) select * from (
select 'Fender' as name
union select 'a'
union ..... ) t
where not exists (select 1 from brand t2 where t2.name COLLATE latin1_general_ci = t.name COLLATE utf8mb4_unicode_ci )