简体   繁体   中英

How to create parent and two child tables mysql

I have a parent table named grade:

classid classname 
   1     classone
   2     classtwo

Two child tables named classone and classtwo.

classone table:

studentid  studentname
   1        john
   2        snow

classtwo table:

studentid studentname
   1         Tyrion
   2         Lannister

How to create these tables with primary key and foreign key?

I am newer in mysql database, Who can help me ?

Add FOREIGN KEY (classId) REFERENCES Grade(classId) to each foreign table:

CREATE TABLE Grade(
    classId INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(classId),
    className VARCHAR(255),
) ENGINE=INNODB;

CREATE TABLE Classone(
    studentId  INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(studentId),
    studentName VARCHAR(255),
    classId CHAR(40),
    FOREIGN KEY (classId) REFERENCES Grade(classId)
) ENGINE=INNODB;

CREATE TABLE Classtwo(
   studentId  INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(studentId),
    studentName VARCHAR(255),
    classId CHAR(40),
    FOREIGN KEY (classId) REFERENCES Grade(classId)
) ENGINE=INNODB;

Remember, you also need to add classId in each foreing table to match them. So i also added two colums for these class tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM