I have a table named SUBJECT with fields SUBJ_ID and SUBJ_NAME. Another table is called COURSES with the fields COURSE_NAME, SUBJ_NAME, and SUBJ_ID. My goal is to automatically update the SUBJ_ID in the COURSE table with the SUBJ_ID from the SUBJECT table when the SUBJ_NAME is entered into the COURSE table.
For example, the SUBJECT table has the following data:
+-----------+-------------+
| course_ID | course_name |
+-----------+-------------+
| 1 | math |
| 2 | physics |
+-----------+-------------+
If I enter into the COURSES table:
INSERT INTO `courses` VALUES('Algebra 101', 'Math');
How can I have it automatically update SUBJ_ID to equal 1?
Change your table schema to something like below:
Course Table
Subject Table
Get rid of the
subj_namein thecoursestable (because its redundant and might lead to data corruption like in your case). This will normalize your data, and you will be able to get the information via joins.If you have a subject table with subj_id and subj_name, then the subj_id should be your primary key (unique identifier). Your second table, courses, should have course_id, course_name and subj_id. The course_id should be your primary key (unique identifier). You will then have a one to many foreign key between subj_id in the subject table to subj_id in your course table.
Once this is set up, you will use this query:
This will pull the course and subject that it belongs to.
When ever you need to update the subject name, you now only have to change it in one place, subject.subj_name, and it will propagate over due to the relationship.
If all this is too much, read up on normalizing data and setting up relationships properly.
Best of luck!