Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql insert into 2 tables

Tags:

mysql

insert

I want to make a insert into 2 tables

visits:

visit_id int | card_id int

registration:

registration_id int | type enum('in','out') | timestamp int | visit_id  int

I want something like:

INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`) 
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);

I wonder if its possible

like image 833
Spidfire Avatar asked Jun 16 '10 13:06

Spidfire


People also ask

Can I insert into 2 tables at once SQL?

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 can insert data into two tables simultaneously in MySQL?

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!

How do you insert data into two tables?

To insert records from multiple tables, use INSERT INTO SELECT statement. Here, we will insert records from 2 tables.

How can insert data in two tables at a time in PHP?

You want to insert data into two tables using PHP and MYSQL table. Yes, it is possible through the one table data insertion process. $query1 = "INSERT INTO table1 ..."; $query2 = "INSERT INTO table2..."; mysqli_query($query1, $cser); mysqli_query($query2, $cser);


2 Answers

It's not possible with one query as INSERT can only insert data to one table in mysql. You can either

  1. write this as two queries and execute them as a batch
  2. create a stored procedure that would execute two insert command

You can wrap those inserts in transaction if you need to make sure that both queries will write the data.

like image 120
RaYell Avatar answered Oct 01 '22 12:10

RaYell


It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?

If so, you can just use the LAST_INSERT_ID() function like this:

INSERT INTO `visits` (`visit_id`,`card_id`) 
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`) 
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
like image 34
Ike Walker Avatar answered Oct 01 '22 12:10

Ike Walker