The basic operation of adding, deleting, modifying and checking the database in MySQL8.0

The basic operation of adding, deleting, modifying and checking the database in MySQL8.0

Article Directory

foreword

The most commonly used additions, deletions, modifications, and queries in MySQL correspond to SQL statements such as insert, delete, update, and select. This kind of data manipulation statement is also called Data Manipulation Statements (data manipulation statement).

1. Description of the default database

Log in to the database first and then execute the show command. The command to view the database isshow databases

[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.31 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

mysql> 

As can be seen from the queried tables, there are three tables in total, all of which are created by the system by default.

1. MySQL database

The core database that comes with the MySQL system, which stores MySQL user account and authority information, some stored procedures , event definition information, some log information generated during operation, some help information, and time zone information, etc.

1.1. information_schema database

information_schema is also the database that comes with the MySQL system. It mainly stores the system information of the MySQL database server, such as the name of the database, the name of the data table, the name of the field, access rights, data files, the folder where it is located, and the folder used by the system. Including which tables, which views, which triggers, columns, indexes.

This information is not real user data, but some descriptive information, sometimes called metadata. Some tables beginning with innodb_sys are provided in the system database info rmation_schema
to represent internal system tables.

1.2.performance_schema 库

performance [pəˈfɔ:məns] performance

"performance_schema" is the built-in database of the MySQL system, which mainly stores some status information during the operation of the MySQL server, and can be used to monitor various performance indicators of MySQL. Including statistics of which statements have been executed recently, how long each stage of the execution process took, memory usage and other information.

This library has been added since MySQL5.5.

1.3.sys library

This library is added after MySQL5.7 version.

The "sys" database is the built-in database of the MySQL system. Its main function is to combine information_schema and performance_schema in the form of views to display various performance indicators of the MySQL database server in an easier-to-understand manner, helping system administrators and developers Monitor the technical performance of MySQL.

2. SQL statements

DDL statement data definition language, used to manage tables

create create

alter modify

drop delete

创建表   create table 表名(字段名1 数据类型 约束条件,字段名2 数据类型 约束条件,...);
 
create table student(id int(20),name char(40),age int);
 
添加,修改,删除表字段
 
删除字段 alter table 表名 drop 字段;
alter table student drop age;
 
查看表结构 show columns from 表名;
show columns from student;
 
添加字段 alter table 表名 add 字段 数据类型 约束条件;
alter table student add age int not null;
 
修改字段 alter table 表名 modify字段名 数据类型 约束条件;
alter table student modify age int null;
 
删除表   drop table 表名;
drop table student;

DML statement data manipulation language, used to manage data

insert add/insert

update modify

delete delete

select query

添加数据   insert into 表名 values (字段值,字段值,字段值...);
insert into student values (1,’张三’,18); 
添加多行数据   insert into 表名 values (字段值,字段值,字段值...),(字段值,字段值,字段值...),(字段值,字段值,字段值...);
 
修改数据   update 表名 set 字段=新值 where 条件
update student set id=2 where name=’张三’;
 
删除数据   delete from student where 条件
delete from student where id=1

DCL statement data control language, used to manage permissions

授权
grant 权限 on 库.表 to '用户' @'IP' identified by '密码';

取消授权
revoke 权限 on 库.表 from '用户' @'IP';

查看某个的用户权限
use mysql;
select * from user where user='用户名称'\G;

查看所有用户权限
select * from user;

2. Operation command of MySQL database

1. Check which databases currently exist show databases;

Syntax: show databases;

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

1: information_schema This database saves the information of all databases of the MySQL server. Such as the database name, the table of the database, the data type of the table column and the access right, etc.

2: performance_schema This is a performance optimization engine added to MySQL5.5: named PERFORMANCE_SCHEMA
#Mainly used to collect database server performance parameters. MySQL users cannot create Table
3 whose storage engine is PERFORMANCE_SCHEMA: the mysql library is a system library, which stores account information, permission information, etc.

1.1. Display in line

show databases \G #以行的方式显示

mysql> show databases \G;
*************************** 1. row ***************************
Database: information_schema
*************************** 2. row ***************************
Database: mysql
*************************** 3. row ***************************
Database: performance_schema
*************************** 4. row ***************************
Database: sys
4 rows in set (0.00 sec)

ERROR: 
No query specified	#未指定查询

2. Create database create

Notes on creating a database:

  • 1. In the file system, the MySQL data storage area will represent the MySQL database in a directory. Therefore, the database name in the above command must be consistent with the operating system's constrained directory name. For example, symbols such as ,/,:,*,?, ", <,>,| are not allowed in file and directory names, and these letters will be automatically deleted in the MySQL database name. <Follow the constraints of the directory>
  • 2. The name of the database cannot exceed 64 characters. Names containing special characters or names consisting entirely of numbers or reserved words must be enclosed in single quotation marks ``.
  • 3. The database cannot be renamed.
Syntax: create database database name;
mysql> create database student;
Query OK, 1 row affected (0.00 sec)

mysql> create database lilinbo;
Query OK, 1 row affected (0.01 sec)

mysql> create database xinghai;
Query OK, 1 row affected (0.06 sec)

The database name also has its own specifications. For example, when the database has a horizontal line, an error will be reported:

mysql> create database lilinbo-grow;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-' at line 1

For this kind of error due to the name, we can use backticks to solve it:

mysql> create database `lilinbo-grow`;
Query OK, 1 row affected (0.01 sec)

The backtick is a symbol introduced to distinguish MYSQL reserved words from ordinary characters.

For example create is a reserved word:

mysql> create database `create`;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| create             |
| information_schema |
| lilinbo            |
| lilinbo-grow       |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)

If you do not use backticks, MYSQL will createtreat them as reserved words and cause errors. Therefore, if there are MYSQL reserved words as fields, you must add backticks to distinguish them.

Quotation marks are generally used in the value of the field, if the field value is a character or a string, you need to add quotation marks, such as: select='field value'

The database or table created without backticks cannot contain MYSQL reserved words, otherwise an error will occur.

Everything in Linux is a file, so where is the created lilinbo database?

[root@localhost ~]# find / -name lilinbo
/usr/local/mysql/data/lilinbo

You can see that this directory is full of databases created by us and the database created by the system:
insert image description here
for the time being, we only need to know that all the created files are here. Let’s take a look at the table structure and data later.

See which commands were executed to create the table:

mysql> show create database student \G;	#查看创建库执行了哪些命令
*************************** 1. row ***************************
       Database: student
Create Database: CREATE DATABASE `student` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */
1 row in set (0.00 sec)

ERROR: 
No query specified

3. Select a database use

If we want to select a database, we can use the use statement. The use statement will select a database as the current database, and the subsequent operations will be performed in the selected database.

Syntax: use database name;
mysql> use lilinbo;	#切换到某个库
Database changed
mysql> show tables;
Empty set (0.00 sec)

You can use select to view the current location:

mysql> select database();
+------------+
| database() |
+------------+
| student    |
+------------+
1 row in set (0.00 sec)

mysql> select database();
+------------+
| database() |
+------------+
| lilinbo    |
+------------+
1 row in set (0.00 sec)

If no database is selected, NULL is displayed by default, and Null means that no database is selected;

4. Delete the database drop

Be careful when deleting data. Here we can use the drop command to delete the database, such as the mufeng-grow just now. Let’s delete it:

Syntax: drop database database name;
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| create             |
| information_schema |
| lilinbo            |
| lilinbo-grow       |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)

mysql> drop database lilinbo;
Query OK, 0 rows affected (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| create             |
| information_schema |
| lilinbo-grow       |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.01 sec)

You can see that there is no prompt when deleting, and it is deleted directly, so you must be careful when deleting the database!

5. Modify the database name

MySQL previously provided a rename database db_old to db_new command to directly rename the database, which may be due to incomplete functions (for example, this command may be a very large transaction, or because there are many previous tables or MyISAM, etc.), Later versions directly canceled this command.

1. Mysqldump is renamed during the process of importing and exporting

Use the mysqldump tool to export from the old library and then import into the new library (the most original, slowest, and easiest to think of) method: the old library yttdb_old export (included objects: tables, views, triggers, events, stored procedures, stored functions )

This method is suitable for use when the amount of data is small.

2. Change the table name of the library

Use MySQL to change the table name to traverse all the tables in the old database in batches and rename them to the tables in the new database.

You can write a script to modify it in batches, which is suitable for use when the amount of data is large.

3. Other operation methods

1. Check your default location when you just logged in to MySQL

mysql> select database();
+------------+
| database() |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)

mysql> 

At this time, it is empty by default;

2. Select the default database on the command line

[root@localhost ~]# mysql -uroot -p123456 lilinbo-grow #指定数据库名
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.31 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select database();#登陆后,就已经在默认数据库里了
+--------------+
| database()   |
+--------------+
| lilinbo-grow |
+--------------+
1 row in set (0.00 sec)

insert image description here

Fourth, the addition, deletion, modification and query of database tables

1. Create a database table create

Starting from MySQL8.0, all innoDB tables

Syntax: create tables table name

Syntax: create table table name (field name type, field name type, field name type); #Create a data table in the current database

mysql> create table xinghai(id int );	#int代表整数类型
Query OK, 0 rows affected (0.04 sec)

mysql> show tables;
+-------------------+
| Tables_in_xinghai |
+-------------------+
| xinghai           |
+-------------------+
1 row in set (0.00 sec)

#创建表,写入数据
mysql> create table test(id int,名字 char(10),年龄 int,性别 char(1));
Query OK, 0 rows affected (0.01 sec)

mysql> desc test;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int(11)  | YES  |     | NULL    |       |
| 名字   | char(10) | YES  |     | NULL    |       |
| 年龄   | int(11)  | YES  |     | NULL    |       |
| 性别   | char(1)  | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)

2. Display the structure (field) information desc of the specified data table in the current or specified database

Syntax: desc table name #Display the structure (field) information of the specified data table in the current or specified database

mysql> desc xinghai;	#显示当前或指定数据库中指定数据表的结构(字段)信息
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.05 sec)

3. Modify the name of the data table alter

Syntax: alter table table name rename new table name; #modify the name of the data table

Syntax: alter table table name drop field; #delete field

Syntax: alter table table name change original field name new field name new field type; #modify field name

Syntax: alter table table name modify field name to be modified type to be modified; #modify field type

Syntax: alter table table name add field name field type; #add field
mysql> alter table students add sex enum('M','W');

mysql> alter table xinghai rename to xxhf;
Query OK, 0 rows affected (0.04 sec)

+-------------------+
| Tables_in_xinghai |
+-------------------+
| xxhf              |
+-------------------+
1 row in set (0.00 sec)

mysql> desc xxhf;;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> alter table xxhf rename xinghai;
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+-------------------+
| Tables_in_xinghai |
+-------------------+
| xinghai           |
+-------------------+
1 row in set (0.00 sec)

4. Insert a new record into the data table insert

Syntax: insert into table name (field 1, field 2, ...) values ​​(value of field 1, value of field 2, ...); #insert a new record into the data table

#创建表,写入数据
mysql> create table test(id int,名字 char(10),年龄 int,性别 char(1));
Query OK, 0 rows affected (0.01 sec)

mysql> desc test;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int(11)  | YES  |     | NULL    |       |
| 名字   | char(10) | YES  |     | NULL    |       |
| 年龄   | int(11)  | YES  |     | NULL    |       |
| 性别   | char(1)  | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)

#插入数据
mysql> insert into test values (1,'张三',18,'男');
Query OK, 1 row affected (0.00 sec)

#只给id和名字插入数据
mysql> insert into test(id,名字) values(2,'李四');
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
+------+--------+--------+--------+
2 rows in set (0.00 sec)

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
+------+--------+--------+--------+
5 rows in set (0.00 sec)

mysql> insert into test(id,年龄) values (3,4),(4,5),(5,6);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    3 | NULL   |      4 | NULL   |
|    4 | NULL   |      5 | NULL   |
|    5 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
9 rows in set (0.00 sec)

5. Delete table content delete

Syntax: delete from table name; #Clear the records in the current database table

Syntax: delete from table name where conditional expression; #delete part of the data

Syntax: delete from table name where condition 1 and condition 2; #Delete data that meets condition 1 and condition 2

#删除一部分数据
mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    3 | NULL   |      4 | NULL   |
|    4 | NULL   |      5 | NULL   |
|    5 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
9 rows in set (0.00 sec)

mysql> delete from test where 年龄=4;
Query OK, 1 row affected (0.01 sec)

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    4 | NULL   |      5 | NULL   |
|    5 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
8 rows in set (0.00 sec)

#删除满足条件的行
mysql> delete from test where id=4 and 年龄=5;
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    5 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
7 rows in set (0.00 sec)

6. Modify and update the records in the data table update

Syntax: update table name set field name = new data where conditional expression; #Modify and update records in the data table

mysql> update test set id=7 where 年龄=6;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    7 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
7 rows in set (0.01 sec)

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |     20 | 男     |
|    3 | 老王   |     21 | 男     |
|    4 | 小莉   |   NULL | NULL   |
+------+--------+--------+--------+
4 rows in set (0.00 sec)

mysql> update test set 年龄=20,性别='女' where id=4 and 名字='小莉';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |     20 | 男     |
|    3 | 老王   |     21 | 男     |
|    4 | 小莉   |     20 | 女     |
+------+--------+--------+--------+
4 rows in set (0.00 sec)

7. Find eligible records in the data table select

Syntax: select * from table name *

Syntax: select field name 1, field name 2... from table name where conditional expression; #Find records that meet the conditions from the data table

mysql> select * from test;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
|    2 | 李四   |   NULL | NULL   |
|    3 | NULL   |   NULL | NULL   |
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    7 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
7 rows in set (0.00 sec)

mysql> select id,年龄 from test;
+------+--------+
| id   | 年龄   |
+------+--------+
|    1 |     18 |
|    2 |   NULL |
|    3 |   NULL |
|    4 |   NULL |
|    5 |   NULL |
|    6 |   NULL |
|    7 |      6 |
+------+--------+
7 rows in set (0.00 sec)

mysql> select id=7 from test where 年龄=6;
+------+
| id=7 |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql> select * from test where id>3;
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    4 | NULL   |   NULL | NULL   |
|    5 | NULL   |   NULL | NULL   |
|    6 | NULL   |   NULL | NULL   |
|    7 | NULL   |      6 | NULL   |
+------+--------+--------+--------+
4 rows in set (0.00 sec)

mysql> select * from test where 性别='男';
+------+--------+--------+--------+
| id   | 名字   | 年龄   | 性别   |
+------+--------+--------+--------+
|    1 | 张三   |     18 | 男     |
+------+--------+--------+--------+
1 row in set (0.00 sec)

8. Delete the specified range of records between...and... in the data table

Syntax: between...and... #Delete the specified range of records in the data table

Five, MySQL data type

Numerical type: integer type, floating point number (decimal type)

Date and time type: year, year, month, day, hour, minute, second, year, month, day, hour, minute, second

String type: text type string, binary type string

1. Numeric type

insert image description here

1.1. Integer type

Integer + -

type storage requirements signed range unsigned range Remark
tinyint tiny integer 1 byte -128~127 0~255 2 to the eighth power
smallint small integer 2 bytes -32768~32767 0~65535 2 to the sixteenth power
mediumint medium size 3 bytes -8399608~8399607 0~2^24-1 2 to the twenty-fourth power
int ordinary 4 bytes -2147483648~2147483647 0~2^32-1 2 to the thirty-second power
bigint oversized 8 bytes 0~2^64-1 2 to the sixty-fourth power

Case 1:

mysql> create table test2 (id tinyint);
#int(2)中(2)表示显示宽度,也就是显示几位数,但是并不严格,即使写入的数值超过了这个宽度只要值不超过数据类型的取值范围就可以正常写入和显示
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+-------------------+
| Tables_in_xinghai |
+-------------------+
| test              |
| test2             |
| xinghai           |
+-------------------+
3 rows in set (0.00 sec)

mysql> insert into test2 values (127);
Query OK, 1 row affected (0.00 sec)
#id的数值是2的八次方范围:-128~127

mysql> desc test2;
+-------+------------+------+-----+---------+-------+
| Field | Type       | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id    | tinyint(4) | YES  |     | NULL    |       |
+-------+------------+------+-----+---------+-------+
1 row in set (0.00 sec)

Case 2:

mysql> create table test3 (a tinyint,b smallint,c mediuminnt,d int,e bigint);
Query OK, 0 rows affected (0.01 sec)

mysql> desc test3;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| a     | tinyint(4)   | YES  |     | NULL    |       |
| b     | smallint(6)  | YES  |     | NULL    |       |
| c     | mediumint(9) | YES  |     | NULL    |       |
| d     | int(11)      | YES  |     | NULL    |       |
| e     | bigint(20)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
#括号内的数字解释
()代表里边数据的长度,按照位数计算长度(比如127是三位数),可以修改长度
(4)含义:里边数据的长度最多能写四位,不能超出这个长度
(6)含义:最多能写六位,不能超出这个长度

1.2. Decimal type (floating point number)

float

float(x, y): single-precision floating-point number, occupying 4 bytes of storage, x is the precision indicating the total number of digits of integers and decimals, y is the scale indicating how many decimals there can be, and the effective digits of x are 6~7

Case 1:
mysql> create table t3(a float(5,2));#5代表数字整个的长度(包括小数点后的数字),第二位代表小数的长度,第一个要比第二个大
Query OK, 0 rows affected (0.00 sec)

mysql> desc t3;
+-------+------------+------+-----+---------+-------+
| Field | Type       | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| a     | float(5,2) | YES  |     | NULL    |       |
+-------+------------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> insert into t3 values(111.222);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t3 values(333.4444);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t3 values(555.666);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t3;
+--------+
| a      |
+--------+
| 111.22 |
| 333.44 |
| 555.67 |
+--------+
3 rows in set (0.00 sec)

mysql> create table t4(id float (6.3));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t4 values(11.23456);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t4 values(3456.7890);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t4 values(22222.1111);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t4 values (112323.45678);
Query OK, 1 row affected (0.00 sec)
mysql> select * from t4;
+---------+
| id      |
+---------+
| 11.2346 |
| 3456.79 |
| 22222.1 |
|  112323 |
+---------+
4 rows in set (0.00 sec)

2. String type

insert image description here
Text type string: limited by the character set. For the uft8 character set, numbers, letters, and symbols all occupy 1 byte, Chinese characters occupy 3 bytes, and characters defined in the unicode character set occupy 2 bytes.

char(M): fixed-length text string, M represents the display width, indicating that a maximum of M characters can be displayed, and the value range of M is 0-255. If the number of characters written is less than the value of M, then a space will be displayed Fill to the number of M. When querying, the filled spaces will be deleted and displayed. If the number of characters written is greater than M, the extra part will be intercepted

varchar(M): Indefinite length text string, M is the display width, which means that at most M characters can be displayed, and the value range of M is 1-21844. If the number of characters written is less than M, no spaces will be added. If the number of characters written is greater than M, the extra characters will be intercepted, or an error will be reported, and varchar will take up an additional 1~2 bytes to record the actual length of characters written. If the number of characters is <=255, use 1 byte, otherwise use 2 bytes

type Support storage size Remark
tinytext very small text strings Maximum support 255 bytes 2^8-1
text small text string Maximum support 65535 bytes 2^16-1
mediumtext medium-sized text string Maximum support 2^24-1 bytes
longtext large text string Maximum support 2^32-1 bytes

Case 1:

mysql> create table t5(name char(5),n varchar(5));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t5 values ('1234a','123ab');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+-------+-------+
| name  | n     |
+-------+-------+
| 1234a | 123ab |
+-------+-------+
1 row in set (0.00 sec)

3. Date and time type

insert image description here

3.1.year: year

Format 1: Expressed in four-digit string format, range '1901'-'2155'

Format 2: represented by four digits, range 1901-2155

Format 3: Expressed in two-digit string format, range '00'-'99'

​' 00'-'69' means '2000'-'2069'

​' 70'-'99' means '1970'-'1999'

Format 4: represented by two digits, range 00-99

​00-69 means 2000-2069

​70-99 means 1970-1999

Case 1:

mysql> create table t6 (a year);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t6 values ('2022'),(2022),('20');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from t6;
+------+
| a    |
+------+
| 2022 |
| 2022 |
| 2020 |
+------+
3 rows in set (0.00 sec)

3.2. time: time

Format 1: 'HH:MM:SS', HH means hour, MM means minute, SS means second

Format 2: 'HHMMSS'

Format 3: 'D HH:MM:SS', D represents the number of days, which will be calculated as the addition of the corresponding hour and the value of HH, and the value range of D is -34~34

The value range of time is -838:59:59-838:59:59

case:

mysql> create table t7(a time);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t7 values ('20:22:26'),('202226'),('122:22:26');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from t7;
+----------+
| a        |
+----------+
| 20:22:26 |
| 20:22:26 |
| 46:22:26 |
+----------+
3 rows in set (0.00 sec)

3.3.date: date

Format 1: 'YYYY-MM-DD', YYYY means year, MM means month, DD means day, the value range is '1000-01-01~9999-12-03'

Format 2: 'YY-MM-DD', YY means year, MM means month, DD means day, YY value range is '00'-'99', '00'-'69' means '2000'-'2069' , '70'-'99' means '1970'-'1999'

Format 3: YYMMDD

case:

mysql> create table t9(a date);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t9 values('2023-03-22'),('23-03-22'),(3230322);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from t9;
+------------+
| a          |
+------------+
| 2023-03-22 |
| 2023-03-22 |
| 2023-03-22 |
+------------+
3 rows in set (0.00 sec)

3.4. datetime: date and time

Format 1: 'YYYY-MM-DD HH:MM:SS', value range: '1010-01-01 00:00:00'~'9999-12:31 99:99:99'

Format 2: 'YY-MM-DD HH:MM:SS', YY value range '00'-'99', '00'-'69' means '2000'-'2069', '70'-'99 ' means '1970'-'1999'

Format three: 'YYYYMMDDHHMMSS', 'YYMMDDHHMMSS'

case:

mysql> create table t8(a datetime);
Query OK, 0 rows affected (0.06 sec)

mysql> insert into t8 values('2023-03-22 22:15:55'),('23-03-22 22:15:55'),(20230322221555);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from t8;
+---------------------+
| a                   |
+---------------------+
| 2023-03-22 22:15:55 |
| 2023-03-22 22:15:55 |
| 2023-03-22 22:15:55 |
+---------------------+
3 rows in set (0.00 sec)

6. MySQL constraints

insert image description here
insert image description here

1. Not null constraint not null

Not empty constraint: not null means that a column cannot store NULL values

If a field is specified with a not-null constraint, the value of the field cannot be empty

Format:

field data type not null

Case: Create a table with a not-null constraint

mysql> create table 非空(id int,name varchar(10) not null));
Query OK, 0 rows affected (0.04 sec)

mysql> desc 非空;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(10) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into 非空 values (1,'a');
Query OK, 1 row affected (0.00 sec)

mysql> insert into 非空(name) values ('b');
Query OK, 1 row affected (0.00 sec)

mysql> select * from 非空;
+------+------+
| id   | name |
+------+------+
|    1 | a    |
| NULL | b    |
+------+------+
2 rows in set (0.00 sec)

2. Unique constraint unique

unique: Requirements must be unique, except null.

If a unique constraint is set for the field, the value of the field must be unique.

Format: Add field data type unique after the data type Add unique (field) after all field definitions are complete

case:

mysql> create table 唯一 (id int unique,name varchar(10));;
Query OK, 0 rows affected (0.01 sec)

mysql> desc 唯一;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  | UNI | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into 唯一 values(1,'a');
Query OK, 1 row affected (0.00 sec)

mysql> insert into 唯一 values(2,'b');
Query OK, 1 row affected (0.00 sec)

mysql> select * from  唯一;
+------+------+
| id   | name |
+------+------+
|    1 | a    |
|    2 | b    |
+------+------+
2 rows in set (0.00 sec)

3. Primary key constraint primary key

Primary key constraint = not null + unique (not empty and unique), ensuring that a column (or a combination of two columns and multiple columns) has a unique identifier, which helps to find a specific record in the table easier and faster.

If the primary key constraint is set for the field, the value of the field cannot be empty and the value is unique, and a joint primary key can be defined.

Format: After directly adding to the data type, the field data type primary key defines all fields and adds them, #If you want to define a joint primary key, you need to use this format to create it.

Case: Create a table with a primary key constraint

mysql> create table 主键约束 (id int primary key,name varchar(10) unique,score int not null);
Query OK, 0 rows affected (0.01 sec)

mysql> desc 主键约束;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(10) | YES  | UNI | NULL    |       |
| score | int(11)     | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

4. Foreign key constraints foregin key

It is used to establish a connection between two data tables. A table can set a foreign key for one field, or set a foreign key for multiple fields. Adding a foreign key indicates that it belongs to a sub-table and is related to the table with a foreign key. The table belongs to the parent table, and the data types of the fields in the relationship between the child table and the parent table must be consistent, and the fields of the parent table must be the primary key.

Foreign Key Constraints: Referential integrity that guarantees that data in one table matches values ​​in another table.

Format: constraint foreign key constraint name foreign key (child table field) references parent table name primary key

Case: Create a table with foreign key constraints


Guess you like

Origin blog.csdn.net/m0_67159981/article/details/130132102