【发布时间】:2020-06-23 17:09:47
【问题描述】:
对于从另一个表返回的每个 id,我需要将多行插入到一个表中。
例如表1
id | thing1 |
---+--------|
1 | true
2 | false
3 | true
4 | false
5 | true
示例表2
id | table1_id | column3 | column4 |
---+-------------|----------------|--------------|
1 | 1 | 'fizz' | 'fizz'
2 | 1 | 'buzz' | 'buzz'
3 | 1 | 'hello world' | 'hello world'
4 | 2 | 'fizz' | 'fizz'
5 | 2 | 'buzz' | 'buzz'
6 | 2 | 'hello world' | 'hello world'
我需要从上面 table1 中获取每一个 id,其中 thing1 为真,并将多行插入到 table2 中,其中包含相应的 id 以及 2 个其他字符串。
SELECT id FROM table1 WHERE thing1 = true
将返回 id 1、3 和 5。
我想插入多行,将 table1 中的 id 以及 2 个其他字符串添加到 table2 中。
INSERT into table2 (table1_id, column3, column4)
VALUES
(*id*, 'fizz', 'fizz')
(*id*, 'buzz', 'buzz')
(*id*, 'hello world', 'hello world')
我知道如何获取 id 和手动插入,但我怎样才能用一个语句来做这两个?
【问题讨论】:
-
这没有任何意义。 Table1 和插入的值有什么关系?价值观从何而来?我认为您需要提供minimal reproducible example。此外,您应该决定使用哪个 DBMS。 mysql sql 服务器
-
最好检查表 2 中的
id数字,它们目前没有实际意义 -
正确标记! SQL Server 和 MySQL 是两个完全不同的产品。这是哪一个?
-
@user3328991 。 . .由于使用双引号分隔字符串,我删除了 SQL Server 标记。