【⑫MySQL | Constraint (2)】Foreign key | Default value | Check constraint — comprehensive case

foreword

✨Welcome to Xiao K 's MySQL column , this section will bring you MySQL foreign keys | default values ​​| check constraints and comprehensive case sharing✨


6. Foreign key constraints (FOREIGN KEY, FK)

The integrity constraints introduced above are all set in a single table, while foreign key constraints ensure the referential integrity between multiple tables (usually two tables), that is, between two fields of two tables reference relationship.

6.1 Concept

There will be a parent-child relationship between the two tables with foreign key constraints, that is, the value range of a field in the child table is determined by the parent table. For example, to represent a department and employee relationship, that is, each department has multiple employees. First, there should be two tables: the department table and the employee table, and then there is a field deptno in the employee table that represents the department number, which depends on the primary key of the department table, so the field deptno is the foreign key of the employee table, through which the department table and The employee table establishes the relationship.

For two tables with an association relationship, the table where the primary key in the associated field is located is the main table (parent table), and the table where the foreign key is located is the secondary table (child table).

When specifically setting the FK constraint, the field for setting the FK constraint must depend on the primary key of the existing parent table in the database, and the foreign key can be NULL.
insert image description here

6.2 Features

  • The foreign key column of the slave table must reference (reference) the primary key or column of the unique constraint of the main table: because the value of the reference must be unique
  • When creating a foreign key constraint, if you do not name the foreign key constraint, the default name is not the column name, but a foreign key name is automatically generated, such as emp11_ibfk_1, you can also specify the foreign key constraint name
  • When creating a table, you must first create the master table, and then create the slave table
  • To delete a table, you must first delete the slave table (or delete the foreign key constraint first), and then delete the main table
  • When the records of the master table are referenced by the slave table, the records of the master table will not be allowed to be deleted. If you want to delete data, you need to delete the records that depend on this field in the slave table first, and then you can delete the records in the master table
  • When creating a foreign key constraint, the system will create a corresponding ordinary index on the column by default; after deleting the foreign key constraint, you must 手动delete the corresponding index

6.3 Add foreign key constraints

Setting the FK constraint of a field in a table is very simple, and its syntax is as follows:

CREATE TABLE table_name(
	字段名 数据类型,
    字段名 数据类型,
    ...
    CONSTRAINT 外键约束名 FOREIGN KEY (字段名1)
    	REFERENCES 主表名 (字段名2)
);

In the above statement, "foreign key constraint name" is used to identify the constraint name, "field name 1" is the field name of the foreign key set in the child table, and "field 2" is the field name in the parent table referenced by the child table.

(1) Add when creating a table

CREATE TABLE 主表名
(
	字段名 数据类型 PRIMARY KEY,
    字段名 数据类型,
    ...
);

CREATE TABLE 从表名
(
    字段名 数据类型 PRIMARY KEY,
    字段名 数据类型,
    ...
    CONSTRAINT 约束名 FOREIGN KEY(外键约束字段名)
    REFERENCES 主表(参考字段名)
);

(1) Add after creating the table

In general, the association between tables is designed in advance, so the foreign key constraints are defined when the table is created. However, if you need to modify the design of the table (such as adding a new field, adding a new relationship), but there is no pre-defined foreign key constraints, then you need to modify the table to supplement the definition.

Format:

ALTER TABLE 从表名 ADD [CONSTRAINT 约束名] FOREIGN KEY(从表字段名) REFERENCES 主表名(被参考字段) [ON UPDATE XX][ON DELETE XX];

example:

ALTER TABLE emp ADD [CONSTRAINT fk_emp_deptno] FOREIGN KEY(deptno) REFERENCES dept(deptno);

6.4 Demonstration

6.4.1 Creating tables

#新建数据库
CREATE DATABASE db_maye;
USE db_maye;

#创建表
CREATE TABLE dept
(
	deptno INT PRIMARY KEY COMMENT '部门编号',
	dname VARCHAR(20) NOT NULL  COMMENT '部门名称',
	loc   VARCHAR(20)  COMMENT '部门所在位置'
);

CREATE TABLE emp
(
	empno INT PRIMARY KEY  COMMENT '员工编号',
	ename VARCHAR(10) NOT NULL  COMMENT '员工姓名',
	deptno INT  COMMENT '员工所在部门编号',	#外键必须使用表级约束
	CONSTRAINT fk_emp_deptno FOREIGN key(deptno) REFERENCES dept(deptno)
);
#必须先创建dept表,再创建emp表,如果没有指定外键,那么随便先创建哪个都行

6.4.2 Operation table

  • add record
#给员工表添加一条记录
INSERT INTO emp(empno,ename,deptno) VALUES(1234,'king',10);
-- 在dept表中不存在10号部门,所以错误->error:无法添加或更新子行:外键约束失败(' db_maye ')。 外键约束:fk_emp_deptno (' deptno ')

#先给dept添加记录,再执行上面的插入语句即可
INSERT INTO dept(deptno,dname,loc) VALUES(10,'C/C++','武汉');
  • Delete Record

#删除主表dept中的记录
DELETE FROM dept WHERE deptno=10;
-- 在从表emp中有部门编号为10的,所以错误->Cannot delete or update a parent row: a foreign key constraint fails...

#先删除从表emp中参考指定值的记录,再执行上面的删除语句即可
DELETE FROM emp WHERE deptno=10;
  • modification record
#修改主表dept中的部门编号(把部门编号为10的改为20)
UPDATE dept SET deptno=20 WHERE deptno=10;
-- 在emp表中有参考dept表的deptno的外键,所以不能修改-> Cannot delete or update a parent row: a foreign key constraint fails...

#可以先删除从表emp中参考指定值的记录,再执行上面的语句
DELETE FROM emp WHERE deptno=10;
  • Add foreign key constraints after table creation
ALTER TABLE emp ADD [CONSTRAINT fk_emp_deptno] FOREIGN KEY(deptno) REFERENCES dept(deptno);
  • drop constraints and indexes
#先查看约束名
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE table_name='emp';

#删除外键约束
ALTER TABLE emp DROP FOREIGN KEY fk_emp_deptno;

#查看指定表的索引
SHOW INDEX FROM emp;
#最后手动删除索引
ALTER TABLE emp DROP INDEX fk_emp_deptno;

6.5 Development Scenarios

Ques 1: If there is a relationship between two tables (one-to-one, one-to-many), such as employee table and department table (one-to-many), must foreign key constraints be established between them?

Answer: No, it works fine without foreign key constraints! !

Ques 2: What is the difference between building a foreign key constraint or not?

Answer:

  • Establish foreign key constraints, and your operations (creating tables, deleting tables, adding, modifying, and deleting data) will be restricted.

    • For example: It is impossible to add an employee information in the employee table, if his department number cannot be found in the department table.
  • Without establishing foreign key constraints, your operations (creating tables, deleting tables, adding, modifying, and deleting data) will not be restricted, but you must also ensure the referential integrity of the data, you can only rely on 程序员的自觉or 在访问的时候进行限定.

    • For example, in the employee table, you can add an employee information even if his department is not in the department table

Ques 3: Does it have anything to do with the query whether to build foreign key constraints or not?

Answer: no

In MySQL, foreign key constraints have a cost and consume system resources. For large concurrent SQL operations, it may not be suitable. Such as the central database of a large website, it may be 因为外键约束的系统开销而变得非常慢. 应用层面Therefore, MySQL allows you to complete the logic of checking data consistency without using the foreign key constraints that come with the system . That is to say, even if you do not use foreign key constraints, you must find a way to implement the function of foreign key constraints through the application layer without additional logic to ensure data consistency.

6.6 Alibaba Development Specification

[Mandatory] Foreign keys and cascading are not allowed, and all foreign key concepts must be resolved at the application layer.

Explanation: deptno in the department table dept is the primary key, then empno in the employee table emp is the foreign key. If you update deptno in the department table and trigger the update of deptno in the employee table at the same time, it is a cascade update. Foreign keys and cascading updates are suitable 单机低并发and not suitable 分布式、高并发集群; cascading updates are strongly blocked, and there are 更新风暴risks to the database; foreign keys affect the insertion speed of the database.

6.7 Cascade operation

When we need to delete the department table (master table) information, we must first delete the associated data in the employee table (slave table), which is very troublesome! ! !

At this time, we can use cascade operation: cascade operation refers to that when you operate the master table, the slave table is automatically operated

two cascade operations

  • Cascading delete: automatically delete related data from the table when deleting the main table data
  • Cascading update: When the foreign key constraint field (usually the primary key) of the main table is updated, the data in the slave table is automatically updated

Five cascading methods

For the ON UPDATE/ON DELETE clause specified when defining the foreign key of the secondary table, InnoDB supports 5 methods, which are listed as follows:

  • CASCADE cascading method

    • When updating/deleting records on the master table, update/delete the matching records from the slave table synchronously
  • SET NULL set to NULL

    • When updating/deleting records on the master table, set the column of matching records on the slave table to NULL
  • NO ACTION updates and deletes are not allowed

    • If there is a matching record from the slave table, it is not allowed to update the associated field of the master table
  • RESTRICT restrictions

    • Same NO ACTION
  • SET DEFAULT

    • When there is a change in the main table, the sub-table sets the foreign key column to a default value, but Innodb does not recognize it...

Example : You can see that the data in the slave table in the figure below changes with the modification of the master table data and the master table is restricted and cannot delete data

CREATE TABLE emp1
(
	empno INT PRIMARY KEY  COMMENT '员工编号',
	ename VARCHAR(10) NOT NULL  COMMENT '员工姓名',
	deptno INT  COMMENT '员工所在部门编号',	#外键必须使用表级约束
	CONSTRAINT fk_emp_deptno FOREIGN KEY(deptno) REFERENCES dept(deptno)
    ON UPDATE CASCADE ON DELETE RESTRICT
);

INSERT INTO emp1(empno,ename,deptno) VALUES(1234,'king',20);
INSERT INTO emp1(empno,ename,deptno) VALUES(234,'ing',20);
INSERT INTO emp1(empno,ename,deptno) VALUES(34,'ng',20);

UPDATE dept SET deptno=30 WHERE deptno=20;

DELETE FROM dept WHERE deptno=30;

insert image description here
insert image description here

7. Default value constraints and check constraints

7.1 Check constraints (Check)

Check whether the value of a field meets the requirements of xx, generally refers to the range of values

MySQL5.7 can use check constraints, but check constraints do not take effect~

MySQL8.0 starts to use the check constraint, it will take effect, and it can be checked correctly

  • Add a check constraint when creating a table, you can add it directly, or add it later (by aliasing), it is more convenient to delete
#1
CREATE TABLE stu
(
	 id INT PRIMARY KEY AUTO_INCREMENT,
	 name VARCHAR(10),
	 gender CHAR CHECK(gender IN('男','女'))
);

#2
CREATE TABLE stu
(
	 id INT PRIMARY KEY AUTO_INCREMENT,
	 name VARCHAR(10),
	 gender CHAR CHECK(gender IN('男','女')),
	 age TINYINT,
	 sal DECIMAL(10,2),
	 CONSTRAINT ck_stu_sal CHECK(sal>200),
	 CONSTRAINT ck_stu_age CHECK(age BETWEEN 18 AND 120)
);
  • Another example
age TINYINT check(age>20) 
或
age TINYINT check(age BETWEEN 18 AND 120) 
  • Add check constraints after table creation
ALTER TABLE stu ADD CONSTRAINT ck_stu_sal CHECK(sal>2000);

remove check constraint

ALTER TABLE stu DROP CHECK ck_stu_sal;

insert image description here

7.2 Default constraint (Default)

When inserting a new record into a database table, if a field is not assigned a value, the database system will automatically insert a default value for this field. In order to achieve this effect, it can be set through the SQL statement keyword DEFAULT.

Setting the default value of a field in a database table is very simple, and its syntax is as follows:

  • When creating the table add
CREATE TABLE df
(
		id INT PRIMARY KEY,
		name VARCHAR(10) DEFAULT 'maye'
);
  • After creating the table add
ALTER TABLE df MODIFY name VARCHAR(10) DEFAULT 'hello';
  • remove default constraints
ALTER TABLE df MODIFY name VARCHAR(10);

insert image description here

8. Comprehensive actual combat

8.1 Create a data table

8.1.1 Table field description

In the autumn, in order to allow students to increase physical exercise, the school began to prepare for the student sports meeting. In order to facilitate the preservation of competition score information, the following data tables are defined.

  • Player table (sporter):
    • Athlete number sporterno, athlete name name, athlete gender gender, department number deptno
  • Sports item table (item):
    • Item number itemno, item name iname, competition location loc
  • Grades:
    • Athlete number sporterno, item number itemno, score mark

insert image description here

There are two foreign keys in the score table: the number of the athlete and the number of the event. The reason for this design is that one athlete can participate in multiple events, and one event can have multiple athletes. Different projects have their own grades. So there is a many-to-many relationship between athletes and projects. The emp-dept learned before is a one-to-many relationship.

8.1.2 Constraints in tables

insert image description here

8.1.3 SQL statement

# 创建数据库
CREATE DATABASE IF NOT EXISTS games1;
USE games1;

CREATE TABLE IF NOT EXISTS spoter
(
	spoterno INT,
	name     VARCHAR(30) NOT NULL,
	gender   CHAR        NOT NULL,
	deptname VARCHAR(30) NOT NULL,
	CONSTRAINT pk_spoterno PRIMARY key(spoterno),
	CONSTRAINT ck_gender   check(gender IN('男','女'))
)COMMENT '运动员表';

CREATE TABLE IF NOT EXISTS item
(
	itemno   INT,
	itemname VARCHAR(30) NOT NULL,
	loc      VARCHAR(30) NOT NULL,
	CONSTRAINT pk_itemno PRIMARY key(itemno)
)COMMENT '项目表';

CREATE TABLE IF NOT EXISTS grade
(
	spoterno INT,
	itemno INT,
	mark INT,
	CONSTRAINT ck_mark CHECK(mark IN(0,2,4,6)),
	CONSTRAINT fk_spoterno FOREIGN key(spoterno) REFERENCES spoter(spoterno),
	CONSTRAINT fk_itemno FOREIGN key(itemno) REFERENCES item(itemno)
)COMMENT '成绩表';


--  添加测试数据
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1001,'rust','男','计算机系');
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1002,'go','男','数学系');
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1003,'python','男','计算机系');
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1004,'c++','男','物理系');
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1005,'c','女','心理系');
INSERT INTO spoter(spoterno,name,gender,deptname) VALUES(1006,'java','女','数学系');

INSERT INTO item(itemno,itemname,loc) VALUES(1,'男子五千米','一操场');
INSERT INTO item(itemno,itemname,loc) VALUES(2,'男子标枪','一操场');
INSERT INTO item(itemno,itemname,loc) VALUES(3,'男子跳远','二操场');
INSERT INTO item(itemno,itemname,loc) VALUES(4,'女子跳高','二操场');
INSERT INTO item(itemno,itemname,loc) VALUES(5,'女子三千米','三操场');

INSERT INTO grade(spoterno,itemno,mark) VALUES(1001,1,6);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1002,1,4);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1003,1,2);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1004,1,0);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1001,3,4);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1002,3,6);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1004,3,2);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1003,3,0);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1005,4,6);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1006,4,4);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1001,4,2);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1002,4,0);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1003,2,6);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1005,2,4);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1006,2,2);
INSERT INTO grade(spoterno,itemno,mark) VALUES(1001,2,0);

SELECT * FROM spoter;
SELECT * FROM item;
SELECT * FROM grade;

8.2 Data manipulation

Question 1 : Find the name of the department with the highest total points and its points.

  1. Identify required datasheets
    1. speaker: department name
    2. grade: points
  2. Identify known associated fields
    1. Far mobilization and points: sporter.sporterno=grade.sporterno
WITH temp AS
(	
	SELECT s.deptname deptname,SUM(g.mark) totalmark
	FROM spoter s,grade g
	WHERE s.spoterno=g.spoterno
	GROUP BY deptname
)
SELECT deptname,totalmark FROM temp
HAVING totalmark=(SELECT MAX(totalmark) FROM temp);

The second question : find out the name of each event and the name of the champion in a playground.

  1. Determining the required data sheet
    #sporter: Name of champion
    #item: Athlete for a playground game
    #grade: Find the champion
  2. Determine the associated field
    #Athletes and points: sporter.sporterno=grade.sporterno
    #Items and points: item.itemno = grade.itemno
WITH temp AS
(	
	SELECT i.itemno,MAX(g.mark) maxmark
	FROM item i,grade g
	WHERE i.itemno=g.itemno AND i.loc='一操场'
	GROUP BY i.itemno
)
SELECT * 
FROM temp t,spoter s,item i,grade g
WHERE g.mark=t.maxmark AND s.spoterno=g.spoterno 
AND i.itemno=g.itemno AND t.itemno=g.itemno;

Question 3 : Find out the names of other students who have participated in the projects that C++ has participated in.
Determine the required data sheet , sporter: c++ , grade: c++ Participated in the project

WITH temp AS
(
	SELECT g.itemno
	FROM spoter s,grade g
	WHERE s.spoterno=g.spoterno
	AND s.name='c++'
)
SELECT DISTINCT s.name
FROM spoter s,grade g
WHERE s.spoterno=g.spoterno 
AND g.itemno IN(SELECT * FROM temp)
AND s.name!='c++';

Question 4 : After investigation, the score of c++ is recorded as 0 because of the use of prohibited drugs. Please make corresponding changes in the database.

UPDATE grade SET mark=0 WHERE spoterno=
(SELECT spoterno FROM spoter WHERE name='c++');

Question 5 : After consultation with the organizing committee, the women's high jump event needs to be deleted. First delete the foreign key in grade

ALTER TABLE grade DROP FOREIGN KEY fk_itemno;
DELETE FROM item WHERE itemname='女子跳高';

Summarize

In general, using constraints can improve the data quality, consistency and integrity of the database, simplify data manipulation, and improve the performance of the database. It is an important concept in database design and management, which helps to ensure the reliability and validity of data ~The next section will share the data types for everyone

Guess you like

Origin blog.csdn.net/qq_72157449/article/details/132386049
Recommended