Home >Database >Mysql Tutorial >How to Retrieve Inserted Row Data in MySQL with a Single Query?
Retrieving Inserted Row Data in MySQL with a Single Query
In relation to the question, it is possible to insert a row and retrieve its inserted values in a single MySQL query, addressing the need to perform multiple subsequent queries for this purpose.
The SQL syntax for achieving this is as follows:
<code class="sql">INSERT INTO `items` (`item`, `number`, `state`) (SELECT '3', `number`, `state` FROM `item_bug` WHERE `id`='3') SELECT * FROM `items` WHERE `id`= LAST_INSERT_ID();</code>
This query first inserts a new row into the items table, selecting the values to be inserted from the item_bug table. It then uses the LAST_INSERT_ID() function within the second SELECT query to retrieve the ID of the newly inserted row. This allows for the immediate retrieval of the inserted data without the need for a separate query.
The above is the detailed content of How to Retrieve Inserted Row Data in MySQL with a Single Query?. For more information, please follow other related articles on the PHP Chinese website!