Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple rows using select

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.

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?

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

like image 389
arbme Avatar asked Mar 20 '11 04:03

arbme


People also ask

Can you insert multiple rows in SQL at once?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

How do you insert 3 rows in SQL?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.


1 Answers

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:

INSERT INTO SomeTable ( Col1, Col2, Col3 )
SELECT Val1, Val2, Val3 FROM SomeOtherTable
UNION
SELECT 'MyProvidedVal1', 'MyProvidedVal2', 'MyProvidedVal3'

Hope that helps...

like image 94
Eric Tarasoff Avatar answered Oct 25 '22 13:10

Eric Tarasoff