MySQL 使用 select 插入多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5366814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert multiple rows using select
提问by arbme
I am trying to insert 2 rows into the same table. The first will input data from a select, the second will use vars for data. I am able to insert the first row but having trouble inserting multiple rows.
我想在同一个表中插入 2 行。第一个将从选择中输入数据,第二个将使用变量作为数据。我能够插入第一行,但无法插入多行。
The $partner_id is to link the rows to each other. For this im using a generated 32char value in php. Is there anyway to set the edit_partner_id with mysql as the id of the first row inserted or is this not possible due to the first row has to be created before you can get the last id?
$partner_id 用于将行相互链接。为此,我在 php 中使用了生成的 32char 值。无论如何,是否可以将 mysql 的 edit_partner_id 设置为插入的第一行的 id 或者这是不可能的,因为必须先创建第一行才能获得最后一个 id?
Is it possible to also add an update to this or would I have to run this in a seperate query?
是否也可以为此添加更新,或者我是否必须在单独的查询中运行它?
$sql = "INSERT INTO edits_customers (customer_id, creator_id, firstname, surname,
house_no, address_1, address_2, address_3, city, county, postcode,
country, email, home_tel, mobile_tel, work_tel, notes, edit_type,
edit_partner_id )
(SELECT *, 'before', '{$partner_id}' FROM customers WHERE customers.id = 123),
('{$var1}', '{$var2}', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', 'after', $partner_id)";
Thanks
谢谢
回答by Eric Tarasoff
If I'm understanding your question correctly, where you're trying to insert some data from another table and some data you provide yourself, you should be able to do something like this using UNION:
如果我正确理解您的问题,您尝试从另一个表插入一些数据以及您自己提供的一些数据,您应该能够使用 UNION 执行以下操作:
INSERT INTO SomeTable ( Col1, Col2, Col3 )
SELECT Val1, Val2, Val3 FROM SomeOtherTable
UNION
SELECT 'MyProvidedVal1', 'MyProvidedVal2', 'MyProvidedVal3'
Hope that helps...
希望有帮助...