Day 32 default default value unique single column unique and union unique primary key primary key auto_increment self-incrementing foreign key foregin key relationship between tables and tables

Constraints
I said before:
zerofill (fill with 0)
unsigned (constraint condition value unsigned unsigned)
not null non-empty (cannot insert empty)

Supplementary knowledge points can be specified when inserting data

create table t1(
    id int,
    name char(16)
    );
insert into t1(name id)values("nana",1)

default default value
default code display

create table t2(
id int,
name char(16),
gender enum("male","female","other")default"male"
);
insert into t2(id,name)values(1,"nana");   gender显示默认为male
insert into t2 values(2,"dada","female");   gender显示为female
desc t2;
select * from t2;

unique

单列唯一
    create table t3(
    id int unique,
    name char(16)
    );
    insert into t3 values(1,"jason"),(1,"dada");    id两都是1,报错
    insert into t3 values(1,"jason"),(2,"dada");    id是唯一的,正常存储
    desc t3;
    select * from t3;
联合唯一
比如ip和port
单个都可以重复 但是加在一起必须是唯一的
联合唯一代码验证
    create table t4(
        id int,
        ip char(16),
        port int,
        unique(ip,port)
        );
    insert into t4 values(1,"127.0.0.1",8080);
    insert into t4 values(2,"127.0.0.1",8081);
    insert into t4 values(3,"127.0.0.2",8080);
    insert into t4 values(4,"127.0.0.1",8080);  报错
    desc t4;
    select * from t4;

Primary key primary key
From the perspective of constraint effect, primary key is equivalent to not null + unique. It is
non-empty and unique! ! !

主键代码验证
    create table t5(id int primary key);
    insert into t5 values(null);    报错
    insert into t5 values(1)(1);   报错
    insert into t5 values(1),(2);   正常
    desc t5;
    select * from t5;

In addition to its constraining effect, it is also the basis for the Innodb storage engine to organize data. The
Innodb storage engine must have a primary key after creating a table
because it is similar to a book catalog that can help prompt query efficiency and is also the basis for building tables.

There is one and only one primary key in a table. If you do not set a primary key, it will search from top to bottom until it
encounters a non-empty and unique field, and it will be automatically upgraded to the primary key.

代码演示
    create table t6(
        id int,
        name char(16),
        age int not null unique,
        addr char(32) not null unique
        );
    
    desc t6;  (age key项自动升级为PRI主键)

If there is no primary key and no other non-empty and unique fields in the table, Innodb will use
a hidden field provided by itself as the primary key. Hidden means that you cannot use it and cannot provide query speed.

A table should usually have a primary key field and the id field is usually used as the primary key

Single field primary key

代码演示
    create table t7(
        id int primary key,
        name char(16)
        );
    desc t7;

Combined primary key (multiple fields combined as the primary key of the table is essentially a primary key)

代码演示
    create table t8(
        id int,
        port int,
        primary key(ip,port)
        );
    desc t8;
我们以后在创建表的时候id字段一定要加primary key(数据的唯一标识)

auto_increment (automatically increase the number of the data)
when there are too many numbers, it is too troublesome to maintain artificially

代码演示
    create table t9(
        id int primary key auto_increment,
        name char(16)
        );
    insert into t9(name) values("jason"),("nana"),("dada");
    select * from t9;
    
注意auto_increment通常都是加在primary key主键上,不能给普通字段加
代码演示
    create table t10(id int auto_increment);    报错
    
总结:
    以后在创建表的id(数据的唯一标识id,uid,sid)字段的时候
    id int primary key auto_increment

补充:
    delete from在删除表中数据的时候,主键的自增不会停止
    truncate t1清空表数据并重置主键
代码演示
    delete from t9;
    insert into t9(name) values("lala");  (id默认是从4开始的)

    truncate t9
    insert into t9(name) values("lala");  (id是重置为0开始的)

The relationship between the table and the table is
defined. An employee table is defined. There are many fields in the table
id name gender dep_name dep_desc

The organization structure of the table is not very clear (negligible)
waste hard disk space (negligible)
data scalability is extremely poor (cannot be ignored)

How to optimize the
above problem is similar to that you write all the code in a py file.
Split the employee table into the employee table and the department table.

Foregin key foreign key
foreign key is used to help us build relationships between tables and tables of
foregin key

There are only 4 relationships between tables at most

一对多关系
    在mysql的关系中没有多对一的说法
    一对多 多对一 都叫一对多
多对多关系
一对多关系
没有关系

One-to-many
relationship The method of judging the relationship between the table and the table. If you are not familiar with it in the early stage, you must follow the principle of empathy and consider from the perspective of the two tables.

Take the employee table and the department table as an example.
Think about whether an employee can correspond to multiple departments (whether one employee data corresponds to multiple department data)
can’t
(you cannot draw a conclusion directly, you must consider both tables completely)
and then stand on the department table to
think Can a department correspond to multiple employees (can the data of a department correspond to multiple employee data)
can
conclude that the
employee table and the department table are one-way one-to-many,
so the table relationship is one-to-many

foreign key
1 One-to-many table relationship foreign key fields are built on the multiple side
2 When creating a table, you must first create the associated table
3 When entering data, you must also enter the associated table first
Insert picture description here

sql statement to establish a table relationship

  create table dep(
        id int primary key auto_increment,
        dep_name char(16),
        dep_desc char(32)
        );      (部门表)
        
    create table emp(
        id int primary key auto_increment,
        name char(16),
        gender enum("male","female","other") default "male",
        dep_id int
        foreign key(dep_id) references dep(id)
        );      (员工表)

    desc dep;
    desc emp;
    

    insert into emp(name,dep_id) values("nana",1);  直接插入emp表会报错,dep_id是外键字段,关联了部门表

    insert into dep(dep_name,dep_desc) values("外交部","流浪法师"),
    ("教学部","教书育人"),
    ("技术部","技术能力部门");
    
    insert into emp(name,dep_id)values("jason",1),
    ("nana",2),("dada",3),("lala",4);   dep表中只绑定3个id,lala绑定第4个id会报错

    insert into emp(name,dep_id)values("jason",1),
    ("nana",2),("dada",3)
    
    select * from dep;
    select * from emp;

Modify the id field in the dep table

update dep set id=200 where id=2;   报错,无法更改

Delete the data in the dep table

delete from dep;    报错,拒绝修改

Modify or delete the data in the table:
1 Delete the employee data corresponding to the teaching department first, and then delete the department. The
operation is too cumbersome

Truly a relationship between 2 data
update on synchronous updates
can be deleted synchronization delete
cascading delete cascading update

foreign key(dep_id) references dep(id) 
on update cascade   # 同步更新(级联更新)
on delete cascade   # 同步删除(级联删除)
create table dep(
    id int primary key auto_increment,
    dep_name char(16),
    dep_desc char(32)
    );

create table emp(
    id int primary key auto_increment,
    name char(16),
    gender enum("male","female","other") default "male",
    dep_id int,
    foreign key(dep_id) references dep(id) 
    on update cascade   # 同步更新(级联更新)
    on delete cascade   # 同步删除(级联删除)
    );

insert into dep(dep_name,dep_desc) values("外交部","流浪法师"),
("教学部","教书育人"),
("技术部","技术能力部门");
insert into emp(name,dep_id)values("jason",1),
("nana",2),("dada",3);

update dep set id=200 where id=2;   # 将id=2的数据修改成id=200
delete from dep where id=1;     # 将id=1的数据删除
select * from dep;
select * from emp;

Many-to-many relationship
book table and author table as an example
Insert picture description here

  create table book(
        id int primary key auto_increment,
        title varchar(32),
        price int,
        author_id int,
        foreign key(author_id) references author(id)
        on update cascade   # 同步更新
        on delete cascade   # 同步删除
        );
        
    create table author(
        id int primary auto_increment,
        name varchar(32),
        age int,
        book_id int,
        foreign key(book_id) references book(id)
        on update cascade   # 同步更新
        on delete cascade   # 同步删除
        );

Creating the manner described above, the two sides are each other are associated with the table, there is no way to create success
in fact, we just want to record the relationship between books and authors
for field-many relationships between tables, foreign key can not be created in two original table
needs You set up a separate one dedicated to store the relationship between the data of the two tables
Insert picture description here

Case code display

create table book(
    id int primary key auto_increment,
    title varchar(32),
    price int);

create table author(
    id int primary key auto_increment,
    name varchar(32),
    age int);

create table book2author(
    id int primary key auto_increment,
    author_id int,
    book_id int,
    foreign key(author_id) references author(id)
    on update cascade
    on delete cascade,
    foreign key(book_id) references book(id)
    on update cascade
    on delete cascade);

desc book2author;

    
book表与author表之间没有直接的关系,book2author这张表作为一张媒介表使用。 
book2author中的book_id与book中的id是一个一对多的关系,
book2author中的author_id与author中的id也是一个一对多的关系。
    insert into book(title,price) values("撩妹大法",9999),("独孤九贱",8888);
    insert into author(name,age) values("nana",16),("dada",18);
    
    select * from book;
    select * from author;
    select * from book2author;
    
    delete from book where id=2;
    select * from book2author;      # 删除book表中的id为2的数据,那么book2author表中的跟book表中id为2关联的数据也被删除了

One-to-one relationship
id name age addr phone hobby email…
If there are too many fields in a table, not all fields can be used for each query

将表一分为二 
    用户表
        用户表
            id name age
        用户详情表
            id addr phone hobby email......
站在用户表
    一个用户表能否对应多个用户详情 不能
站在详情表
    一个详情能否属于多个用户 不能
    
   结论:
    单向的一对多都不成立 那么这个时候两者之间的表关系
    就是一对一
    或者是没有关系(好判断)

The customer table and the student table
are customers between your registrations and students
after registration (some customers will not sign up during the period).
One-to-one foreign key fields can be built on either side, but it is recommended to build them in a table with a high frequency of query
Insert picture description here

Case code demonstration

   create table authordetail(
        id int primary key auto_increment,
        phone int,
        addr varchar(64)
        );
    
    create table author1(
        id int primary key auto_increment,
        name varchar(32),
        age int,
        authordetail_id int unique,
        foreign key(authordetail_id) references authordetail(id)
        on update cascade
        on delete cascade
        );
    desc author1;
    desc authordetail;
    

to sum up

表关系的建立需要用foreign key
    一对多
        外键字段建在多的一方
    多对多
        自己开设第三张存储
    一对一
        建在任意一方都可以 但是推荐建在查询频率较高的表中

判断表之间的关系方式
    换位思考!!!
    员工与部门
    图书与作者
    作者与作者详情

Modify the table (understand)

  mysql对大小写是不敏感的(mysql是不区分大小写的)
    修改表名
        alter table 表名 rename 新表名;
        
    增加字段
        alter table 表名 add 字段名 字段类型(宽度) 约束条件;
        alter table 表名 add 字段名 字段类型(宽度) 约束条件 first;     # 新建字段在最前面
        alter table 表名 add 字段名 字段类型(宽度) 约束条件 after 字段名;     # 新建的字段跟在哪个字段名的后面 
    删除字段
        alter table 表名 drop 字段名;
    修改字段
        alter table 表名 modify 字段名 字段类型(宽度)约束条件;     # 修改字段名中的字段类型或者是约束条件
        
        alter table 表名 change 旧字段名 新字段名 字段类型(宽度)约束条件;   # 更换新的字段名,更换新的字段类型和约束条件

Copy table (understand)

我们sql语句的结果其实也是一张虚拟表
	create table 表名 select * from 旧表名;  # 只能复制表结构和数据,不能复制主键 外键 索引...
	create table 表名 select * from 旧表 where 条件;  # 按照条件复制表中的数据建成新表(如果条件不成立,那么会直接复制表结构,数据为空

Guess you like

Origin blog.csdn.net/Yosigo_/article/details/113781956