Use SELECT statement to insert rows and columns with custom values
TheINSERT 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:
Select the desired column:
SELECT
clause to include only the required columns: <code class="language-sql">SELECT name, location</code>
Set custom value for gid:
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>
Complete query:
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>
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!