【问题标题】:SQL Insert multiple rows for every id returned from another table if the row does not exist for that idSQL 为从另一个表返回的每个 id 插入多行,如果该行不存在该 id
【发布时间】: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 标记。

标签: mysql sql


【解决方案1】:

我建议像这样插入... SELECT:

INSERT into table2 (table1_id, column3, column4)
SELECT t1.id, s.str, s.str
FROM table1 AS t1
CROSS JOIN (SELECT "fizz" AS str UNION SELECT "buzz" UNION SELECT "hello world") AS s
LEFT JOIN table2 AS t2 ON t1.id = t2.table1_id AND s.str = t2.column3
WHERE t1.thing1 = true
    AND t2.id IS NULL -- Only insert when they are not already present
;

但是,这并不能保证字符串按照您显示的顺序插入。

我没有太多使用 CROSS JOIN 的电话,所以我不确定它们在 LEFT JOIN 方面的表现如何,所以如果上面的方法不太正确,下面是一些替代方法:

INSERT into table2 (table1_id, column3, column4)
SELECT t1.id, s.str, s.str
FROM table1 AS t1
CROSS JOIN (SELECT "fizz" AS str UNION SELECT "buzz" UNION SELECT "hello world") AS s
WHERE t1.thing1 = true
    AND (t2.id, s.str) NOT IN (SELECT table1_id, column3 FROM table2 )
;

INSERT into table2 (table1_id, column3, column4)
SELECT t1.id, s.str, s.str
FROM table1 AS t1
CROSS JOIN (SELECT "fizz" AS str UNION SELECT "buzz" UNION SELECT "hello world") AS s
WHERE t1.thing1 = true
    AND NOT EXISTS (
           SELECT * 
           FROM table2 AS t2 
           WHERE t2.table1_id = t1.id AND t2.column3 = s.str
        )
;

如果是Sql Server,联合子查询(包括它的括号和别名)可以替换为(VALUES ('fizz'), ('buzz'), ('hello word')) AS s(str)

【讨论】:

  • 把我刚刚加到最后的那句话也记下来。
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 2015-07-15
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多