如何将外键添加到 Table 作为列

How do I add Foreign Key to the Table as a column

我有两个 table 如下:

Table 姓名:table_1

ID studentId Date enrolled parent name parents annual income
1 12345 2022/01/13 14:39:15 enrolled ABC 12345
2 12345 2022/01/13 14:39:06 not-enrolled ABC 10345
3 12345 2022/01/13 8:03:44 not-enrolled ABC 1467

我正在努力重构这个 table,因为它有一些缺陷和冗余数据。此外,此 table 中提及的日期为 VARCAR(20)。

我想将其重构为 2 tables,如下所示:

Table A --每个学号只能报名一次,在table报名的第一天,最新在校状态学生姓名和家长姓名(将 table_1 中的条目设为粗体)

Table 姓名:table_2

ID studentId strat_date enrolled parent name
1 12345 2022/01/13 8:03:44 enrolled ABC

Table B -- 其余历史数据

Table 姓名:table_3

ID studentId_1 Date parents annual income
1 1 2022/01/13 14:39:15 12345
2 1 2022/01/13 14:39:06 10345
3 1 2022/01/13 8:03:44 1467

“table_2”table 中的“ID”列是主键。 “table_3”table 中的“studentId_1”列是外键。

我知道如何创建 table_2。

INSERT IGNORE INTO table_2 (studentId, `start_date`, `status`, `parent name`)
SELECT studentId, MIN(`Date`), MIN(enrolled), `parent name`
FROM table_1
GROUP BY studentId, `parent name`;
SELECT * FROM table_2;

给出输出:

ID studentId strat_date enrolled parent name
1 12345 2022/01/13 8:03:44 enrolled ABC

如何创建 table_3,因为它在 table 中有“外键”,如下所示:

ID studentId_1 Date parents annual income
1 1 2022/01/13 14:39:15 12345
2 1 2022/01/13 14:39:06 10345
3 1 2022/01/13 8:03:44 1467
CREATE TABLE table_1 (
    ID INT,
    studentId INT,
    `Date` DATETIME,
    enrolled VARCHAR(255),
    `parent name` VARCHAR(255),
    `parents annual income` INT
);
INSERT INTO table_1 VALUES
(1, 12345,  '2022/01/13 14:39:15',  'enrolled', 'ABC',  12345),
(2, 12345,  '2022/01/13 14:39:06',  'not-enrolled', 'ABC',  10345),
(3, 12345,  '2022/01/13 8:03:44',   'not-enrolled', 'ABC',  1467),
(4, 67890,  '2022/01/12 14:39:15',  'enrolled', 'DEF',  12345),
(5, 67890,  '2022/01/14 14:39:06',  'not-enrolled', 'DEF',  10345),
(6, 67890,  '2022/01/14 8:03:44',   'not-enrolled', 'DEF',  1467);
SELECT * FROM table_1;
CREATE TABLE table_2 (
    ID INT AUTO_INCREMENT,
    studentId INT,
    `start_date` DATETIME,
    `status` VARCHAR(255),
    `parent name` VARCHAR(255),
    PRIMARY KEY (ID),
    UNIQUE (studentId)
);
CREATE TABLE table_3 (
    ID INT AUTO_INCREMENT,
    studentId_Id INT,
    `Date` DATETIME,
    enrolled VARCHAR(255),
    `parents annual income` INT,
    PRIMARY KEY (ID),
    CONSTRAINT fk_studentId_Id  FOREIGN KEY (studentId_Id) REFERENCES table_2 (ID) 
        ON DELETE CASCADE 
        ON UPDATE CASCADE
);

将数据从 table_1 插入 table_2:

INSERT IGNORE INTO table_2 (studentId, `start_date`, `status`, `parent name`)
SELECT studentId, MIN(`Date`), MIN(enrolled), `parent name` 
FROM table_1
GROUP BY studentId, `parent name`;
SELECT * FROM table_2;

将数据从 table_1 插入 table_3 与 table_2 相关:

INSERT INTO table_3 ( studentId_Id, `Date`, enrolled, `parents annual income`)
SELECT t1.ID, t2.`Date`, t2.enrolled, t2.`parents annual income` 
FROM table_2 AS t1, table_1 as t2
WHERE t1.studentId = t2.studentId;
SELECT * FROM table_3;