开发者

Transfer data from one MySQL table to another w/ parameters

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 f开发者_如何学Collowing 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

+-----------+---------+------------+
| course_id | subbj_id|course_name |
+-----------+---------+------------+
|     1     | 1       |  math      |
|-----------+---------+----------- +  

Subject Table

+-----------+-----------+
| subj_id   | subj_name |
+-----------+---------+-+
|     1     |  math     | 
|-----------+-----------+

Get rid of the subj_name in the courses table (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:

select c.course_name, s.subj_name from courses AS c inner join subject AS s on c.subj_id = s.subj_id;

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜