MySQL插入后触发将第一个表的数据插入第二个表

时间:2014-11-18 07:08:45

标签: mysql triggers

Here are my tables.

Student Table
+++++++++++++++++++++++++++++++++++++++++++++++++++
| s_id |    name     |   lname    | fname    | c_id |
+++++++++++++++++++++++++++++++++++++++++++++++++++
|  1   |     ali     |   ahmadi   | ahmad    |  1   |
|  2   |  Hussain    |   Sharan   | Skekib   |  2   |
|  3   |  Mahmood    | Shekibayee | Jahangir |  1   |
+++++++++++++++++++++++++++++++++++++++++++++++++++

Student_course Table
+++++++++++++++++++++++
| sc_id | s_id | c_id  |
++++++++++++++++++++++
|  1    |  1   |   1   |
|  2    |  2   |   1   |
|  3    |  3   |   2   |
++++++++++++++++++++++

Now I want to have a trigger that:
When I insert new student into `student` table it should insert `s_id` and `c_id` into student_Course
table.
I am quite new to PHP and MySQL; any help will be highly appreciated.
Thanks in advance.

1 个答案:

答案 0 :(得分:0)

假设sc_idStudent_course上自动递增的主键

,这可能相当简单
delimiter //
create trigger ins_student_course after insert on Student
for each row 
begin
 insert into Student_course (s_id,c_id) values (new.s_id,new.c_id);
end ;//

delimiter ;