Home > Database > Mysql Tutorial > How to Insert Rows with Custom Values Using INSERT WITH SELECT?

How to Insert Rows with Custom Values Using INSERT WITH SELECT?

Linda Hamilton
Release: 2025-01-18 19:53:11
Original
694 people have browsed it

How to Insert Rows with Custom Values Using INSERT WITH SELECT?

Use SELECT statement to insert rows and columns with custom values

The

INSERT WITH SELECT statement allows customizing the values ​​inserted into the target table by manipulating the SELECT part of the query. This allows you to select specific columns for insertion and set explicit values ​​for other columns.

Your query wants to insert only the name and location columns from the source table into the target table courses, while setting the gid column to a custom value. To achieve this, follow these steps:

  1. Select the desired column:

    • Modify the SELECT clause to include only the required columns:
    <code class="language-sql">SELECT name, location</code>
    Copy after login
  2. Set custom value for gid:

    • Add an extra column to the SELECT clause and assign the desired value to gid. For example, if you want to set gid to 1:
    <code class="language-sql">SELECT name, location, 1 AS gid</code>
    Copy after login
  3. Complete query:

    • Make sure the target table columns and SELECT columns match correctly:
    <code class="language-sql">INSERT INTO courses (name, location, gid)
    SELECT name, location, 1 AS gid
    FROM courses
    WHERE cid = $cid</code>
    Copy after login

By following these steps, you can use the INSERT WITH SELECT statement to insert selected columns into the target table while setting another column to a specified custom value.

The above is the detailed content of How to Insert Rows with Custom Values Using INSERT WITH SELECT?. 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