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

后端 未结 3 1802
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 20:30

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          


        
相关标签:
3条回答
  • 2021-01-17 21:02

    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.

    0 讨论(0)
  • 2021-01-17 21:06

    try this:

    INSERT INTO student_fees(id, name, fees) 
    Select 1, name,'200$' from students 
    
    0 讨论(0)
  • 2021-01-17 21:16

    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
    
    0 讨论(0)
提交回复
热议问题