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
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.
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.
It is also possible to only insert data in specific columns.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With