MySQL learning (four) data definition DDL language

1. Library management

  1. The creation of the library
    create database [if not exists] library name [character set character set name];

    #案例:创建库Books
    create database books;
    create database if not exists books;
    
  2. Modification of the library
    alter database library name character set character set name;

    #更改库的字符集
    ALTER DATABASE books CHARACTER SET utf8;
    ALTER DATABASE books CHARACTER SET gbk;
    

    Rename the library:
    Insert picture description here

  3. Deletion of the library
    drop database [if exists] library name;

    drop database if exists books;
    

Second, the management of the table

  1. Table creation:

    grammar:

    create table 表名(
     	列名 列的类型【(长度) 约束】,
     	列名 列的类型【(长度) 约束】,
     	列名 列的类型【(长度) 约束】,
     	...
     	列名 列的类型【(长度) 约束】
    )
    
    CREATE TABLE IF NOT EXISTS stuinfo(
    	id INT PRIMARY KEY,
    	stuname VARCHAR(20),
    	sex CHAR(1),
    	age INT DEFAULT 18,
    	seat INT UNIQUE,
    	majorid INT,
    	CONSTRAINT fk_stuinfo_major FOREIGN KEY(majorid) REFERENCES major(id)#外键
    );
    
  2. Table modification:

    grammar:

    alter table 表名 add|drop|modify|change column 列名 【列类型 约束】;
    添加列:alter table 表名 add column 列名 类型 【first | after 字段名】;
    修改列的类型或约束:alter table 表名 modify column 列名 新类型 【新约束】;
    修改列名:alter table 表名 change column 旧列名 新列名 类型;
    删除列:alter table 表名 drop column 列名;
    修改表名:alter table 表名 rename 【to】 新表名;
    
    1. Modify column name
      alter table table name change column old column name new column name type;

      alter table book change column publishdate pubdate datetime;
      
    2. Modify column type or constraint
      alter table table name modify column column name new type [new constraint];

      #添加主键
      alter table stuinfo modify column id int primary key;
      
    3. Add a new column
      alter table table name add column column name type [first|after field name];

      alter table author add column annual double;
      
    4. Delete column
      alter table table name drop column column name;

      alter table author drop column annual;
      ALTER TABLE book_author DROP COLUMN  annual;
      
    5. Modify the table name
      alter table table name rename [to] new table name;

      alter table author rename to book_author;
      
  3. Delete
    table : drop table [if exists] table name;

    drop table if exists book_author;
    drop table book_author;
    
  4. Table replication:

    1. Only copy the structure of the
      table : create table table name like old table;

      create table copy_author like author;#没有数据
      
    2. Copy table structure + data
      create table table name select query list from old table [where filter];

      create table copy2_author select * from author;
      
    3. Copy only part of the data

      create table copy3_author select id,au_name 
      from author where nation = '中国';
      

Three, common data types

  1. Integer:

    classification:

    • tinyint、smallint、mediumint、int/integer、bigint
      Insert picture description here

    Features :

    1. If you do not set unsigned or signed, the default is signed, if you want to set unsigned, you need to add the unsigned keyword
    2. If the inserted value exceeds the range of the integer, an out of range exception will be reported, and the critical value will be inserted
    3. If the length is not set, there will be a default length. The
      length represents the maximum width of the display. If it is not enough, it will be filled with 0 on the left, but it must be used with zerofill! , Which is unsigned by default at this time
    create table tab_int(
    	t1 int,#如果不设置长度,会有默认的长度,int型的默认长度为11
    	t2 int(7) unsigned ,#插入无符号整型
    	t3 int(7) zerofill  #使用zerofill关键字,最大宽度如果不够会用0在左边填充
    )
    
    insert into tab_int values(123,123,123);
    select * from tab_int;
    

    search result:
    Insert picture description here

  2. Floating point type:

    classification:

    1. Floating point type
      float(M,D)
      double(M,D)
    2. Fixed-point
      dec(M,D)
      decimal(M,D)

      Insert picture description here

    Features:

    • M represents the number of integer part + decimal part, D represents the decimal part
    • If it exceeds the range, an out or range exception will be reported, and the critical value will be inserted
    • Both M and D can be omitted, but for fixed-point numbers, M defaults to 10 and D defaults to 0
    • If the accuracy requirements are higher, the fixed-point number will be given priority
    create table tab_float(
    	f1 float(5,2),
    	f2 double(5,2),
    	f3 decimal(5,2)
    )
    
    insert into tab_float values(123.45,123.45,123.45);
    insert into tab_float values(123.456,123.456,123.456);# 超过小数位数,四舍五入
    insert into tab_float values(123.4,123.4,123.4);
    select * from tab_float;
    

    search result:
    Insert picture description here

  3. Character type:

    classification:

    • Shorter text:
      char
      varchar
    • Others:
      binary and varbinary are used to save shorter binary
      enums to save enumeration
      sets to save collections
    • Longer text:
      text
      blob (larger binary)

    Features:

    • char: fixed-length character, written as char(M), the maximum length cannot exceed M, where M can be omitted, and the default is 1
    • varchar: variable-length character, written as varchar(M), the maximum length cannot exceed M, and M cannot be omitted
    create table tab_char(
    	c1 enum('a','b','c')
    )
    INSERT INTO tab_char VALUES('a');
    INSERT INTO tab_char VALUES('b');
    INSERT INTO tab_char VALUES('c');
    INSERT INTO tab_char VALUES('m');# 插入失败
    INSERT INTO tab_char VALUES('A');
    
    create table tab_set(
    	s1 set('a','b','c','d')
    );
    INSERT INTO tab_set VALUES('a');
    INSERT INTO tab_set VALUES('A,B');
    INSERT INTO tab_set VALUES('a,c,d');
    
  4. Date type:

    classification:

    • date only saves the date
    • time only saves time
    • year only saves the year
    • datetime save date + time
    • timestamp save date + time
      Insert picture description here

    Features:

      					字节		范围				时区等的影响
      datetime			8			1000——9999年			不受
      timestamp			4			1970-2038年				受
    
    create table tab_date(
    	t1 datetime,
    	t2 timestamp
    );
    insert into tab_date values(now(),now());
    select * from tab_date;
    

Four, common constraints

meaning:

  • A restriction, used to limit the data in the table, in order to ensure the accuracy and reliability of the data in the table

Category: Six Constraints

  • not null: not null, used to ensure that the value of the field cannot be null. Such as name, student number, etc.
  • default: Default, used to ensure that the field has a default value. Such as gender.
  • primary key: The primary key, used to ensure that the value of the field is unique and non-empty. Such as student ID, employee ID, etc.
  • unique: unique, used to ensure that the value of the field is unique and can be empty. Such as seat number.
  • check: check constraints [not supported in mysql]. Different age and gender.
  • foreign key: foreign key, used to restrict the relationship between the two tables, used to ensure that the value of the field must come from the value of the associated column of the main table. Add a foreign key constraint from the table to apply the value of a column in the main table. For example, the professional number of the student table, the department number of the employee table, and the type of work number of the employee table.

Categories added by constraints:

  • Column-level constraints: all six constraints are supported grammatically, but foreign key constraints have no effect
  • Table-level constraints: except for non-empty and default, all others are supported
position Supported constraint types Is it possible to name a constraint
Column-level constraints Behind the column Grammars are supported, but外键没有效果 Can't
Table-level constraints Below all columns 默认和非空不支持, Other support Yes (the primary key has no effect)

(1) Add constraints when creating a table

  1. Add column-level constraints:

    • Syntax: directly append the constraint type after the field name and type.
    • Only supports: default, non-empty, primary key, unique (supported except for foreign keys)
    create table major(
    	id int primary key,
    	majorName varchar(20)
    )
    
    create table stuinfo(
    	id int primary key,#主键
    	stuName varchar(20) not null unique,# 非空,唯一
    	gender char(1) check(gender='男' or gender='女'),#检查约束
    	seat int unique,# 唯一约束
    	age int default 18,#默认约束
    	majorId int references major(id) #外键约束,但列级约束中没有效果
    );
    
  2. Add table-level constraints:

    • Syntax: at the bottom of each field
      [constraint constraint name] constraint type (field name)
    • Except for non-empty and default, everything else is supported
    create table stuinfo(
    	id int,
    	stuname varchar(20),
    	gender char(1),
    	seat int,
    	majorid int,
    	constraint pk primary key(id),#主键
    	constraint uq unique(seat), #唯一键
    	constraint ck check(gender='男' or gender='女'),
    	constraint fk_stuinfo_major foreign key(majorid) references major(id)#外键
    )
    
  3. General writing:

    CREATE TABLE IF NOT EXISTS stuinfo(
    	id INT PRIMARY KEY,
    	stuname VARCHAR(20),
    	sex CHAR(1),
    	age INT DEFAULT 18,
    	seat INT UNIQUE,
    	majorid INT,
    	CONSTRAINT fk_stuinfo_major FOREIGN KEY(majorid) REFERENCES major(id)#在表级约束中定义外键约束
    );
    
  4. Foreign key features

    1. Requires that the foreign key relationship is set in the slave table
    2. The type of the foreign key column of the slave table and the type of the associated column of the main table must be consistent or compatible, and the name is not required
    3. The associated column of the main table must be a key (usually a primary key or unique)
    4. When inserting data, first insert the main table, and then insert the secondary table; when deleting data, first delete the secondary table, and then delete the main table
      • Method 1: cascade delete
        ALTER TABLE stuinfo ad CONSTRAINT fk_stu_major 
        FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE CASCADE;
        
        When deleting, the rows corresponding to the master table and the slave table are deleted.
      • Method 2: cascade blank
        ALTER TABLE stuinfo ad CONSTRAINT fk_stu_major 
        FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE SET NULL;
        
        When deleting, the row corresponding to the main table is deleted, and the null value becomes null from the place where the table is introduced.

(2) Add constraints when modifying the table

grammar:

1、添加列级约束
alter table 表名 modify column 字段名 字段类型 新约束;
2、添加表级约束
alter table 表名 add 【constraint 约束名】 约束类型(字段名) 【外键的引用】;
  1. Add non-empty constraint

    alter table stuinfo modify column stuname varchar(20) not null;
    
  2. Add default constraints

    alter table stuinfo modify column gender char(1) default '男';
    
  3. Add primary key

    列级约束
    alter table stuinfo modify column id int primary key;
    表级约束
    alter table stuinfo add primary key(id);
    
  4. Add unique

    列级约束
    alter table stuinfo modify column seat int unique;
    表级约束
    alter table stuinfo add unique(seat);
    
  5. Add foreign key

    alter table stuinfo add constraint fk_stuinfo_major 
    foreign key(majorid) references major(id); 
    

(Three) delete constraints when modifying the table

  1. Remove non-empty constraints

    alter table stuinfo modify column stuname varchar(20);
    
  2. Remove default constraints

    alter table stuinfo modify column gender char(1);
    
  3. Delete primary key

    alter table stuinfo drop primary key;
    
  4. Delete only

    alter table stuinfo drop index seat ;
    
  5. Delete foreign key

    alter table stuinfo drop foreign key fk_stuinfo_major;
    

5. Identification column (self-increasing)

Also known as self-increasing column.
Meaning: You don’t need to manually insert values, and the system provides default sequence values.

Features:

1、标识列必须和主键搭配吗?不一定,但要求是一个key
2、一个表可以有几个标识列?至多一个!
3、标识列的类型只能是数值型
4、标识列可以通过 SET auto_increment_increment=3;设置步长;
   可以通过 手动插入值,设置起始值
  1. Set the identity column when creating the table

    drop table tab_identity;
    create table tab_identity(
    	id int primary key auto_increment,
    	name varchar(20)
    );
    insert into tab_identity values(NULL,'john');# 插入null表示为自增长
    
    SHOW VARIABLES LIKE '%auto_increment%';
    #设置标识列的步长
    SET auto_increment_increment = 3
    
  2. Set the identity column when modifying the table

    alter table tab_identity modify column id int primary key auto_increment;
    
  3. Delete the identity column when modifying the table

    alter table tab_identity modify column id int;
    

Guess you like

Origin blog.csdn.net/weixin_44630656/article/details/113838537