简体   繁体   中英

is insert based on select on one of the column in MySQL possible?

Is following insert based on select on one of the column possible in MySQL

INSERT INTO student_fees(id, name, fees) 
VALUES(1, SELECT name from students where student_id = 1, 200$) 

If yes then and example will really help.

-Thanks

Try INSERT...SELECT statement

INSERT INTO student_fees(id, name, fees) 
SELECT ... -- put here the SELECT STATEMENT with condition

if your column ID is auto incremented , you don't have to specify the 1 or else it will cause you an error.

INSERT INTO student_fees(name, fees) 
SELECT `name`, '200$' 
FROM students         -- this will select all students on the table
                      -- and add $200 on thier fees.

Another point is, if you only want to insert one column from the student 's table, you need yo specify the condition, so you will not get constraint error ( assuming your column ID is the Primary Key )

INSERT INTO student_fees(name, fees) 
SELECT `name`, '200$' 
FROM   students
WHERE  columnName = 'blahBlah'

UPDATE 1

Seeing your comment, you have this query

INSERT INTO coupon_allotment (page_id, offer_id, coupon_code, user_id) 
SELECT page_id, 4, 'ABC'        -- number of columns mismatch, right?
FROM pages_discounts_association 
WHERE discount_id = 4

you need to remove the user_id column above OR you need to add an ID in your select statement in order to match the number of columns.

Just use the regular INSERT INTO ... SELECT syntax and select the other fields as constants as follows:

INSERT INTO student_fees(id, name, fees) 
SELECT 1, `name`, '200$' FROM students

try this:

INSERT INTO student_fees(id, name, fees) 
Select 1, name,'200$' from students 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM