![](/img/trans.png)
[英]SQL Query to return only one row when id is found in multiple rows from another table
[英]SQL Insert multiple rows for every id returned from another table if the row does not exist for that id
我需要為另一個表中的每個返回的 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 為 true,並將多行插入 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 並手動插入,但如何用一個語句同時完成?
我會建議一個 INSERT ... 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)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.