relation
- Create score table scores, the structure is as follows
- id
- student
- suject
- score
- Thinking: What information should be stored in the student column?
- Answer: The data of the student column is not newly created here, but should be referenced from the student table, and the relationship is also a piece of data; according to the requirements of the paradigm, the student's number should be stored, not the student's name and other information
- Similarly, the chart of accounts is also a relational column, referencing the data in the chart of accounts
- The statement to create the table is as follows
create table scores( id int primary key auto_increment, study int , subid int, score decimal(5,2) );
foreign key
- Thinking: How to ensure the validity of relational column data? Is any integer ok?
- Answer: It must be the data existing in the id column in the student table, and the validity of the data can be verified through foreign key constraints
- Add foreign key constraint for stuid
alter table scores add constraint stu_sco foreign key(stuid) references students(id);
- When inserting or modifying data at this time, if the value of stuid does not exist in the students table, an error will be reported
- Constraints can be created directly when creating a table
create table scores( id int primary key auto_increment, study int , subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );
Cascading operations on foreign keys
- When deleting the data of the students table, if the id value already exists in the scores, an exception will be thrown
- It is recommended to use logical delete, which can also solve this problem
- You can specify cascading operations when you create a table, or you can modify the cascading operations of foreign keys after you create the table
- grammar
alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;
- Types of cascading operations include:
- restrict: default value, throw exception
- cascade (cascading): if the record of the main table is deleted, the associated records from the table will be deleted
- set null: set the foreign key to null
- no action: do nothing