SQL INSERT with SELECT: Customizing Column Values
Often, you'll use SELECT
statements within INSERT
queries to populate tables with data. But what if you need to insert values from the SELECT
query while modifying a specific column's value?
Modifying Column Values During Insertion
This is easily achievable. Let's say you want to insert data from an existing courses
table, but you want to override the gid
column with a specific value:
Original approach (without customization):
INSERT INTO courses (name, location, gid) SELECT name, location, gid FROM courses WHERE cid = $cid
Customized insertion:
INSERT INTO courses (name, location, gid) SELECT name, location, 1 -- gid is now always 1 FROM courses WHERE cid = 2
As you can see, by replacing the gid
column selection with a constant value (in this case, 1
), you directly control the gid
value for all inserted rows. Simply substitute 1
with your desired value and adjust the WHERE
clause (cid = 2
) as needed to select the appropriate source rows. This provides flexibility in populating your table while maintaining control over individual column values.
The above is the detailed content of Can I Customize Column Values During SQL INSERT Using SELECT?. For more information, please follow other related articles on the PHP Chinese website!