Click here to Skip to main content
15,905,875 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
Hi,
i have two sql tables and i have to insert values into these two tables such that a record in primary table is associated with several records in foreign key table.Pls help me.god bless you
Posted
Comments
What have you tried?where is the problem?

Suppose you have two tables:

TAB_TEACHER
- id_teacher // primary key, autoincrement
- name_teacher // a varchar

TAB_STUDENT
- id_student // primary key, autoincrement
- name_student // a varchar
- id_teacher_fk // foreign key reference to a teacher (TAB_TEACHER)

Now - INSERT a new Student with an pre-existin TEACHER, so I have to get the foreign key with a teacher name as:

SQL
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1
 
Share this answer
 
Comments
faizel s 12-Jan-14 14:05pm    
thank you for trying to help me.i think you did'nt get my question properly.I mean that i have to insert values both tables such that foreign key table has many records which refer to only single record in primary key.from your example i can say if id_teacher has value 1,then in the table TAB_STUDENT there will be many rows with id_teacher_fk value 1.i have to insert them all in a single insert statement
A primary key value must exist first before it can be used as foreign key in another table. For example:
To insert students into student table whose teacherid is "james123", you have to ensure that this "james123" already exists in the teacher table otherwise you have to insert this teacher first, e.g.
INSERT INTO teacher (teacherid, teachername) VALUES ('james123','James')

After inserting the teacher then can you insert new students whose teacher is 'james123', e.g.
INSERT INTO student (studentid, studentname, teacherid) VALUES ('student1','name of student1','james123')

For block insert, you should follow the solution by Christian Graus.
 
Share this answer
 
v2
If you want to insert them all in a single insert statement, you can do that easily, by creating many sets of Values as in

insert into tabstudent('fred', 1'), ('bill', 1)

else

this has NOTHING to do with foreign keys, nor does it make ANY difference in the long run if you do many inserts in one statement, or one at a time. All that matters is that your primary keys need to exist before you use them as foreign keys.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900