Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into multiple tables in one query

Assuming that I have two tables, names and phones, and I want to insert data from some input to the tables, in one query. How can it be done?

like image 810
yossi Avatar asked Oct 05 '10 01:10

yossi


People also ask

Can we insert data into multiple tables using single query?

The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.

How do I insert data into multiple tables at once?

No, you can't insert into multiple tables in one MySQL command. You can however use transactions. BEGIN; INSERT INTO users (username, password) VALUES('test', 'test'); INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!

Can I insert into 2 tables at once SQL?

Insert can only operate on one table at a time. Multiple Inserts have to have multiple statements.


2 Answers

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

START TRANSACTION; INSERT INTO table1 VALUES ('1','2','3'); INSERT INTO table2 VALUES ('bob','smith'); COMMIT; 

http://dev.mysql.com/doc/refman/5.1/en/commit.html

like image 102
Joshua Smith Avatar answered Sep 19 '22 18:09

Joshua Smith


MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...) INSERT INTO PHONES VALUES(...) 
like image 32
OMG Ponies Avatar answered Sep 19 '22 18:09

OMG Ponies