Home > Database > Mysql Tutorial > body text

## How to Retrieve Inserted Data in the Same MySQL Query?

Barbara Streisand
Release: 2024-10-26 22:02:29
Original
855 people have browsed it

## How to Retrieve Inserted Data in the Same MySQL Query?

Getting Content after MySQL Insert

Inserting rows into a MySQL table is straightforward. However, retrieving the values inserted in the same query can be a challenge. This question explores the possibility of accomplishing both tasks in a single query.

The question poses a scenario where a row from the 'item_bug' table needs to be inserted into the 'items' table, and the inserted data, including the ID, needs to be retrieved. The proposed solution is to insert the row using an INSERT statement and then retrieve it using a subsequent SELECT statement.

However, the question seeks a more efficient solution by performing both tasks in a single query. To achieve this, the answer suggests using the 'LAST_INSERT_ID()' function. This function returns the ID of the last row inserted into the table. By combining the insert and select statements, it becomes possible to retrieve the inserted data without needing a separate query.

The suggested query would look like this:

INSERT INTO `items` (`item`, `number`, `state`) (SELECT '3', `number`, `state` FROM `item_bug` WHERE `id`='3');
SELECT * FROM `items` WHERE `id`= LAST_INSERT_ID();
Copy after login

By executing this query, the row from 'item_bug' is inserted into 'items,' and the inserted data, including the ID, is immediately retrieved and returned as the result of the query. This solution eliminates the need for a separate query to retrieve the inserted data, making it a more efficient and elegant approach.

The above is the detailed content of ## How to Retrieve Inserted Data in the Same MySQL Query?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!