[英]Transfer data from one MySQL table to another w/ parameters
I have a table named SUBJECT
with fields SUBJ_ID
and SUBJ_NAME
.我有一个名为
SUBJECT
的表,其中包含SUBJ_ID
和SUBJ_NAME
字段。 Another table is called COURSES
with the fields COURSE_NAME
, SUBJ_NAME
, and SUBJ_ID
.另一个表名为
COURSES
,其中包含字段COURSE_NAME
、 SUBJ_NAME
和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.我的目标是在将
SUBJ_NAME
输入到COURSE
表中时,使用SUBJECT
表中的SUBJ_ID
自动更新COURSE
表中的SUBJ_ID
。
For example, the SUBJECT
table has the following data:例如,
SUBJECT
表有以下数据:
+-----------+-------------+
| course_ID | course_name |
+-----------+-------------+
| 1 | math |
| 2 | physics |
+-----------+-------------+
If I enter into the COURSES
table:如果我进入
COURSES
表:
INSERT INTO `courses` VALUES('Algebra 101', 'Math');
How can I have it automatically update SUBJ_ID
to equal 1?我怎样才能让它自动更新
SUBJ_ID
等于 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).摆脱
courses
表中的subj_name
(因为它是多余的,并且可能会像您的情况一样导致数据损坏)。 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).如果您有一个带有 subj_id 和 subj_name 的主题表,那么 subj_id 应该是您的主键(唯一标识符)。 Your second table, courses, should have course_id, course_name and subj_id.
你的第二个表,课程,应该有 course_id、course_name 和 subj_id。 The course_id should be your primary key (unique identifier).
course_id 应该是您的主键(唯一标识符)。 You will then have a one to many foreign key between subj_id in the subject table to subj_id in your course table.
然后,您将在主题表中的 subj_id 与课程表中的 subj_id 之间拥有一对多的外键。
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.当您需要更新主题名称时,您现在只需在一个地方更改它,subject.subj_name,它会由于关系而传播。
If all this is too much, read up on normalizing data and setting up relationships properly.如果这一切都太多了,请阅读规范化数据和正确设置关系。
Best of luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.