Y
Y
yellow_pus2022-01-15 02:49:28
SQL
yellow_pus, 2022-01-15 02:49:28

How to insert into table using foreign key?

Let's say there are 2 tables, with strings in brackets: teacher(id,name) and student(teacher_id,name), where the teacher_id string uses a foreign key from the teacher's id database. Please help, what query can be used to insert values ​​into the student table when adding a new student?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2022-01-15
@rozhnev

create table teacher(
  id int primary key,
  name varchar(64)
);

create table student(
  teacher_id int, 
  name varchar(64), 
  foreign key (teacher_id) references teacher(id)
);

insert into teacher (id, name) values (1, 'Teacher');

insert into student (teacher_id, name) values (1, 'Me');

select *
from student s
join teacher t on t.id = s.teacher_id
;

Test SQL query online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question