SQL INSERT批次插入方式

大白菜!發表於2024-07-03

1、常規INSERT寫法

INSERT INTO ... VALUES (...);

INSERT INTO 表名( `欄位1`, `欄位2`) VALUES ('欄位1的值', '欄位2的值');

2、SELECT語句返回值INSERT

INSERT INTO ...VALUES (..., (select ...));

INSERT INTO 表名1(`欄位1`, `欄位2`)
VALUES (欄位1的值, (select 查詢欄位 from 表名2 where 條件));

也可以變化為查詢多個欄位,再新增資料

INSERT INTO ...VALUES (select ...);

INSERT IGNORE INTO `表名1` (
`欄位1`,
`欄位2`
)
SELECT
`欄位3` AS 欄位1,
'欄位4' AS 欄位2
FROM `表名2` WHERE 條件
注意:查詢出來必須只有一個行

3、批次多行INSERT

INSERT INTO ... VALUES (...), (...),(...);

INSERT INTO 表名(欄位1, 欄位2)
VALUES (欄位1資料, 欄位2資料),
(欄位1資料, 欄位2資料),
(欄位1資料, 欄位2資料);

或者多行查詢後新增

INSERT INTO ... VALUES (...,select...), (...,select...),(...,select...);
INSERT INTO 表名1(`欄位1`, `欄位2`)
VALUES
(欄位1的值, (select 查詢欄位 from 表名2 where 條件)),
(欄位1的值, (select 查詢欄位 from 表名3 where 條件)),
(欄位1的值, (select 查詢欄位 from 表名4 where 條件));

或者使用union all:

INSERT INTO ...
(SELECT ...,(select ...) ) union all
(SELECT ...,(select ...) ) union all
(SELECT ...,(select ...) );
INSERT INTO 表名1 (`欄位1`, `欄位2`)
(SELECT 欄位1的值,(select 查詢欄位 from 表名2 where 條件) FROM 表名3 WHERE 條件) union all
(SELECT 欄位1的值,(select 查詢欄位 from 表名2 where 條件) FROM 表名3 WHERE 條件) union all
(SELECT 欄位1的值,(select 查詢欄位 from 表名3 where 條件) FROM 表名4 WHERE 條件);

相關文章