Home >Database >Mysql Tutorial >How to Insert Data with Default Values Using Nested SELECT Statements in MySQL?

How to Insert Data with Default Values Using Nested SELECT Statements in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 19:13:10403browse

How to Insert Data with Default Values Using Nested SELECT Statements in MySQL?

Inserting Data with Default Values Using Nested SELECT

Inserting data into a MySQL table from another table while assigning default values to certain columns can be achieved using a nested SELECT statement.

In the provided queries, the first one encounters an error because the column list in the main INSERT statement does not match the number of columns returned by the subquery. The second one generates a column count mismatch error because the main INSERT statement specifies four columns, while the VALUES() clause only provides three values.

To rectify this issue, use the following syntax:

INSERT INTO def (catid, title, page, publish) 
SELECT catid, title, 'page','yes' from `abc`

In this modified query:

  • The main INSERT statement specifies the columns into which data will be inserted.
  • The subquery retrieves data from the 'abc' table and selects the 'catid' and 'title' columns.
  • The 'page' and 'publish' columns in the main INSERT statement are assigned the default values of 'page' and 'yes', respectively.

The above is the detailed content of How to Insert Data with Default Values Using Nested SELECT Statements in MySQL?. 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