Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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

like image 893
Abhishek Dhote Avatar asked Aug 10 '12 09:08

Abhishek Dhote


People also ask

Can insert be used with select?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

How do I insert data into a specific column in MySQL?

First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

Is it possible to only insert data in specific columns?

It is also possible to only insert data in specific columns.


1 Answers

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.

like image 197
John Woo Avatar answered Sep 21 '22 19:09

John Woo