Home > Database > Mysql Tutorial > body text

How Can I Insert Multiple Rows into a Table Using a Subquery in MySQL?

DDD
Release: 2024-11-01 03:17:02
Original
452 people have browsed it

How Can I Insert Multiple Rows into a Table Using a Subquery in MySQL?

INSERTing Multiple Rows with a Subquery in MySQL

You're seeking a solution to populate a table with multiple rows returned by a subquery. The example query you've provided attempts to achieve this using a nested VALUES clause, but it results in an error due to the subquery returning more than one row.

Resolving the Error

To overcome this issue, you need to avoid nesting the subquery within the VALUES clause. Instead, combine the subquery with a static value for the name using the following approach:

INSERT INTO Results (People, names)
SELECT d.id, 'Henry'
FROM Names f
JOIN People d ON d.id = f.id
Copy after login

This query will return multiple rows with the id from the subquery combined with the static string 'Henry' for the name column.

Explanation

By combining the subquery and the static value in the SELECT clause, you're effectively creating a single row for each row returned by the subquery. This allows the INSERT statement to successfully add these rows to the Results table.

The above is the detailed content of How Can I Insert Multiple Rows into a Table Using a Subquery in MySQL?. 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
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!