Home > OS >  how to insert values in table2 with reference of table 1
how to insert values in table2 with reference of table 1

Time:01-14

I am trying to write a query to insert values in table2 with reference to table1 using a foreign key.table2 columns are (quesid(primary key/auto-increment), ques,ques_desc). There is another table table1 its primary key is foreign key which is also AUTO INCREMENT. So using that i was trying to insert values. I have written below query:

 insert into users_ques values("What is JAVA","Please SHare the details") 
 from users WHERE quesid = 1;

mysql is giving me error at WHERE (where is not valid at this position). please help me so that i can sucessfully write this query.

CodePudding user response:

The correct way to use select for insert

insert into users_ques (column1,column2)
select column1,column2 
from users
where quesid = 1;

CodePudding user response:

That is not a valid MySQL INSERT syntax. You either do:

INSERT INTO users_ques 
    VALUES ("What is JAVA","Please SHare the details");

OR

INSERT INTO users_ques 
    SELECT "What is JAVA","Please SHare the details" FROM users WHERE quesid = 1;

The way you're doing it now is just combining the two method together.

Demo fiddle

  •  Tags:  
  • Related