Chapter 3 Multi-table Operation 2 (primary and foreign key constraints)

1 How to distinguish between main table and sub table?

        The parent table sets a primary key, and the child table sets a foreign key

       When a one-to-many relationship is established between two tables , the "one" end is the parent table, and the "many" end is the child table.

Such as students and classes

Which class does a student belong to? The student table is the child table and the class table is the main table

Which department does an employee belong to? The employee table is a child table, and the department table is the main table

 

2How to establish the main external construction constraints

FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
 外键 p_id 参照 主表Persons 的主键 (P_Id)

3 The main external constraints need to create tables and data changes

-- 创建班级表
CREATE TABLE class(
c_id INT NOT NULL AUTO_INCREMENT,
c_name VARCHAR(22) ,
c_type INT ,
c_desc VARCHAR(122),
PRIMARY KEY(c_id)
);

-- 创建子表
/**
 先创建主表,在创建 子表
 先删除子表,在删除主表
*/ 
CREATE TABLE student(
s_id INT NOT NULL AUTO_INCREMENT,
s_name VARCHAR(22),
s_sex CHAR(2),
s_address VARCHAR(122),
c_id INT ,
PRIMARY KEY(s_id),
FOREIGN KEY(c_id) REFERENCES class(c_id)	
);

-- 插入数据
/*
在子表插入数据时,保证外键,在主表有数据的存在
*/
INSERT INTO class VALUES (NULL,'3班',2,'xxxxxxxx');
INSERT INTO student VALUES (NULL,'张三','男','北京市,xxxx,',1);
INSERT INTO student VALUES (NULL,'张三2','男','北京市,xxxx,',2);

-- 删除数据
/*
删除数据时,如果是主表,那么在子表中没有关联的数据才可以删除
*/
DELETE FROM class WHERE c_id=1;
DELETE FROM student WHERE s_id =3 ;

-- 更新
/*
更新子表中的外键,要保证主表中有对应的数据
*/
UPDATE class SET c_name='3班' WHERE c_id=3;
UPDATE student SET c_id=4 WHERE s_id=4;

 

4 other constraints

NOT NULL - 指示某列不能存储 NULL 值。
UNIQUE - 保证某列的每行必须有唯一的值。
PRIMARY KEY - NOT NULL 和 UNIQUE 的结合。确保某列(或两个列多个列的结合)有唯一标识,有助于更容易更快速地找到表中的一个特定的记录。
FOREIGN KEY - 保证一个表中的数据匹配另一个表中的值的参照完整性。(上面讲解过)
CHECK - 保证列中的值符合指定的条件。
DEFAULT - 规定没有给列赋值时的默认值。

Details: 

http://www.w3school.com.cn/sql/sql_constraints.asp

 

Guess you like

Origin blog.csdn.net/yipianfeng_ye/article/details/89888289