Home  >  Article  >  Database  >  How to Retrieve Inserted Row Data in MySQL with a Single Query?

How to Retrieve Inserted Row Data in MySQL with a Single Query?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 03:24:02502browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn