mysql- table describes the relationship (focus on the development and application of knowledge)

Relationships between tables (focus)

foreign key (foreign key)

Foreign key constraints for the primary key field pointing to another table

When you create a table, you need to create a master table, creating the table

# 创建主表
create table dept(id int primary key auto_increment,
                 mananger char(10),
                  content char(100)
                 );

# 创建表的时候添加外键
create table student3(id int primary key auto_increment,
                     name char(10),
                      gender char(10),
                      dept_id int,
                      # 绑定外键,绑定主表的id
                      foreign key (dept_id) references dept(id)  
                     );

foreign key (dept_id) references dept(id)
# dept_id  表示当前的外键字段
# dept 表示要关联哪个表
# dept(id) id 表示关联的dept表的id 字段

# 删除从表时,要先删除从表,否则会报错
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails

foreign key constraint action brought

  • Inserting a record from the table, the id associated with a master table does not exist, will be in error; must ensure that the foreign key value table is present in the primary table

  • Insert sequence data

    First insert the main table recorded in the recording sheet inserted from

  • When the table is updated from the foreign key, foreign key value must also ensure that the primary table is present then

  • Before deleting master table records, to ensure that no foreign key to be deleted from the table id

    It must first remove, and then delete the table from the main table

  • When updating the primary key master table records, to ensure that no foreign key to be deleted from the table id

  • You must create a master table

foreign key is used to ensure the association between the two tables is correct

Cascade operation (Cascade)

Cascade operation refers to, when you operate the main table, the automatic operation from the table

Two kinds cascade operation

  • Delete cascade

    Related data is automatically deleted from the table when the main table to delete

  • Cascading update

    When the master key master table updates automatically updates the associated data from the table.

# 创建从表,绑定级联关系
create table student(id int primary key auto_increment,
                     name char(10),tea_id int, 
                     foreign key(tea_id) references teacher(id) 
                     on update cascade 
                     on delete cascade  
                    );
# on update cascade 绑定级联更新
# on deletc cascade 绑定级联删除
# 两个可以单独使用,也可以一起使用,用空格隔开即可
Query OK, 0 rows affected (0.65 sec)

# 添加信息
insert into student values (null,"jack",1),(null,"rose",1),(null,"rayn",2);
Query OK, 3 rows affected (0.16 sec)
Records: 3  Duplicates: 0  Warnings: 0
# 删除老师表中第一个信息
delete from teacher where id = 1;
Query OK, 1 row affected (0.08 sec)

mysql> select * from teacher;
+----+------+
| id | name |
+----+------+
|  2 | nick |
+----+------+
1 row in set (0.00 sec)
# 学生表中,绑定的对应id的信息也会自动删除
mysql> select * from student;
+----+------+--------+
| id | name | tea_id |
+----+------+--------+
|  3 | rayn |      2 |
+----+------+--------+
1 row in set (0.00 sec)


# 表建好后需要在添加外键或者级联操作,可以使用
# alter table 表名 add constraint 外键名称 foreign key (外键字段) references 关系表名(关系表内字段)
alter table student add constraint class_id foreign key(class_id) references class(id) on update cascade on delete cascade;

Using foreign keys

When using foreign keys?

There is any relationship between tables

First, we must clarify the relationship between tables

Many-to (many)

Treatment

老师和部门的关系 
老师的角度看(多)
    一个老师应该对应有一个部门 
    一个老师可以对应对多个部门?  不行 一个老师只能属于一个部门 (要看具体业务要求)!
    多个老师可以对应一个部门 
    多对一
部门的角度看 (一)
    一个部门可以对应多个老师
    一个部门可以对应一个老师
    多个部门可以对应一个老师? 不行 
    一对多 
如何处理一对多(多对一)?
    在老师表中存储 部门id
    即多的一方存储 一的一方的id

In a multi-party, i.e. the corresponding teacher table stores sector number (one of a) a

#部门:
    create table dept(
        id int primary key auto_increment,
        name char(20),
        job char(50),
        manager char(10)
    );
    #老师表:
    create table teacher(
        id int primary key auto_increment,
        name char(20),
        gender char(1),
        dept_id int,
        foreign key(t_id) references teacher(id),
    );

Many to many

How to determine many relationship

For example: teachers and students table table

Teacher angle: a teacher can correspond to multiple students

The perspective of students: a student may also correspond to multiple teachers

If both partners are many relationship, the two are so many relationship

Disposition:

  • Create two main tables as students and teachers
  • Create table contains two fields, each foreign key, the corresponding table pointing
  • The two fields, primary key as the

Establishing an intermediate table for storing relations, comprising at least two fields, point to teachers and students of primary keys, foreign keys are two fields as follows:

You must first establish two main table to table to establish relations

#先创建老师表和学生表,再创建关系表
create table teacher(id int primary key auto_increment, name char(10));
create table student(id int primary key auto_increment, name char(10));
create table tea_stu_a(
        tea_id int,
        stu_id int,
        foreign key (tea_id) references teacher(id),
        foreign key (stu_id) references student(id),
        primary key (tea_id,stu_id)
);

+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| tea_id | int(11) | NO   | PRI | 0       |       |
| stu_id | int(11) | NO   | PRI | 0       |       |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.01 sec)

# 插入老师信息
insert into teacher values (null,"jerry"),(null,"nick");
# 插入学生信息
insert into student values (null,"jack"),(null,"rose");

# 添加关系表信息
insert into tea_stu_a values (1,1);
insert into tea_stu_a values (1,2);
insert into tea_stu_a values (2,1);
insert into tea_stu_a values (2,2);

+--------+--------+
| tea_id | stu_id |
+--------+--------+
|      1 |      1 |
|      2 |      1 |
|      1 |      2 |
|      2 |      2 |
+--------+--------+
# 如何通过关系表查找信息,比如要找出Jerry老师教过的学生
# 1.通过名字获取Jerry老师的id
# 2.拿着id去关系表中拿到学生的id
# 3.通过学生的id取出学生的信息

select * from student where id = any(
        select stu_id from tea_stu_a where tea_id =any(
        select id from teacher where name = "jerry")
);
+----+------+
| id | name |
+----+------+
|  1 | jack |
|  2 | rose |
+----+------+

# 在id=后面加any,否则会报错
ERROR 1242 (21000): Subquery returns more than 1 row

One relationship

Standing on the table are two angles one to one relationship

Treatment

  • Determine the order,
  • The pre-existing data as the main table
  • After the table present as
  • Id to keep the two tables correspondence
    • Method 1: From the table, i.e., id is the primary key and a foreign key
    • Method 2: the id of the table is a foreign key, and guaranteed to be unique
# 人员表
create table person(
    id int primary key auto_increment,
    name char(10),
    age int
);
# 详情表 
create table person_info(
    id int primary key,
    height float,
    weight float,
    foreign key(id) references person(id)
);
#再这样的关系中 必须先插入主表即person 拿到一个id 在添加详情表的数据  

#将一条完整数拆分到不同表中,可以提高查询的效率,上述方式称之为垂直分表!

Guess you like

Origin www.cnblogs.com/raynduan/p/11444663.html