Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql: Insert a row and get the content

Tags:

mysql

insert

Is it possible to insert a row and get the values inserted in the same query?

Something like...

INSERT INTO `items` (`item`, `number`, `state`)  (SELECT '3', `number`, `state` FROM `item_bug` WHERE `id`='3') 

And then, get ID and execute a

SELECT * FROM `items` WHERE `id`='$id' 

But using only one query.

like image 682
Ivan Avatar asked Mar 25 '11 13:03

Ivan


People also ask

How can we fetch data from one table and insert into another table in MySQL?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How do I insert data into a specific row in MySQL?

When inserting a single row into the MySQL table, the syntax is as follows: INSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.


2 Answers

Execute your insert statement and then you can do this:

SELECT * FROM `items` WHERE `id`= LAST_INSERT_ID() 
like image 62
Joe Stefanelli Avatar answered Sep 26 '22 04:09

Joe Stefanelli


you can call a stored procedure which will perform the insert and return a resultset in a single call from your app layer to mysql:

Stored procedure call

mysql> call insert_user('bar'); +---------+----------+ | user_id | username | +---------+----------+ |       1 | bar      | +---------+----------+ 1 row in set (0.02 sec)  $sqlCmd = sprintf("call insert_user('%s')", ...); 

Simple example:

drop table if exists users; create table users ( user_id int unsigned not null auto_increment primary key, username varchar(32) unique not null ) engine=innodb;   drop procedure if exists insert_user;  delimiter #  create procedure insert_user ( in p_username varchar(32) ) begin declare v_user_id int unsigned default 0;   insert into users (username) values (p_username);   set v_user_id = last_insert_id();   -- do more stuff with v_user_id e.g. logs etc...   select * from users where user_id = v_user_id;  end#  delimiter ;  call insert_user('bar'); 
like image 35
Jon Black Avatar answered Sep 23 '22 04:09

Jon Black