MySQL learning (four) data definition DDL language
1. Library management
-
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;
-
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:
-
Deletion of the library
drop database [if exists] library name;drop database if exists books;
Second, the management of the table
-
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)#外键 );
-
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】 新表名;
-
Modify column name
alter table table name change column old column name new column name type;alter table book change column publishdate pubdate datetime;
-
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;
-
Add a new column
alter table table name add column column name type [first|after field name];alter table author add column annual double;
-
Delete column
alter table table name drop column column name;alter table author drop column annual; ALTER TABLE book_author DROP COLUMN annual;
-
Modify the table name
alter table table name rename [to] new table name;alter table author rename to book_author;
-
-
Delete
table : drop table [if exists] table name;drop table if exists book_author; drop table book_author;
-
Table replication:
-
Only copy the structure of the
table : create table table name like old table;create table copy_author like author;#没有数据
-
Copy table structure + data
create table table name select query list from old table [where filter];create table copy2_author select * from author;
-
Copy only part of the data
create table copy3_author select id,au_name from author where nation = '中国';
-
Three, common data types
-
Integer:
classification:
- tinyint、smallint、mediumint、int/integer、bigint
Features :
- 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
- 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
- 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:
- tinyint、smallint、mediumint、int/integer、bigint
-
Floating point type:
classification:
- Floating point type
float(M,D)
double(M,D) - Fixed-point
dec(M,D)
decimal(M,D)
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:
- Floating point type
-
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');
- Shorter text:
-
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
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 supportYes (the primary key has no effect)
(1) Add constraints when creating a table
-
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) #外键约束,但列级约束中没有效果 );
-
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)#外键 )
- Syntax: at the bottom of each field
-
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)#在表级约束中定义外键约束 );
-
Foreign key features
- Requires that the foreign key relationship is set in the slave table
- 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
- The associated column of the main table must be a key (usually a primary key or unique)
- 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
When deleting, the rows corresponding to the master table and the slave table are deleted.ALTER TABLE stuinfo ad CONSTRAINT fk_stu_major FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE CASCADE;
- Method 2: cascade blank
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.ALTER TABLE stuinfo ad CONSTRAINT fk_stu_major FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE SET NULL;
- Method 1: cascade delete
(2) Add constraints when modifying the table
grammar:
1、添加列级约束
alter table 表名 modify column 字段名 字段类型 新约束;
2、添加表级约束
alter table 表名 add 【constraint 约束名】 约束类型(字段名) 【外键的引用】;
-
Add non-empty constraint
alter table stuinfo modify column stuname varchar(20) not null;
-
Add default constraints
alter table stuinfo modify column gender char(1) default '男';
-
Add primary key
列级约束 alter table stuinfo modify column id int primary key; 表级约束 alter table stuinfo add primary key(id);
-
Add unique
列级约束 alter table stuinfo modify column seat int unique; 表级约束 alter table stuinfo add unique(seat);
-
Add foreign key
alter table stuinfo add constraint fk_stuinfo_major foreign key(majorid) references major(id);
(Three) delete constraints when modifying the table
-
Remove non-empty constraints
alter table stuinfo modify column stuname varchar(20);
-
Remove default constraints
alter table stuinfo modify column gender char(1);
-
Delete primary key
alter table stuinfo drop primary key;
-
Delete only
alter table stuinfo drop index seat ;
-
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;设置步长; 可以通过 手动插入值,设置起始值
-
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
-
Set the identity column when modifying the table
alter table tab_identity modify column id int primary key auto_increment;
-
Delete the identity column when modifying the table
alter table tab_identity modify column id int;