MySQL8 commonly used commands DDL, DML statements, constraints

DDL: (Data Definition Language) data definition language
DML: (Data Manipulation Language) data manipulation language

One, the creation of the table (DDL)

1. Grammar
create table 表名 (
	字段名1 数据类型,
	字段名2 数据类型,
	字段名3 数据类型
);
2. Common data types in mysql
type of data meaning
char Fixed length character string (maximum 255), storage space is fixed, and has nothing to do with actual data. Improper use may result in wasted space.
varchar Variable-length character string (maximum 255), will dynamically allocate storage space according to the actual data length, which saves more space.
int Integer (maximum 11)
bigint Long integer
float Floating point (single precision)
double Floating point (double precision)
date Short date type
datetime Long date type
clob Character Larger Object (Character Larger Object) can store up to 4G of strings, such as articles and instructions
blob Binary Larger Object (Binary Larger Object) is specifically used to store streaming media data such as pictures, sounds, and videos. Need to use IO stream when inserting data.
3. Insert data (DML)

3.1 Insert a piece of data:

	insert into 表名(字段1,字段2,字段3...) values(值1,值2,值3...);

3.2 Insert multiple pieces of data:

	insert into 表名(字段1,字段2,字段3...) values(值1,值2,值3...),(值1,值2,值3...),()...;

  • The field name and value must be one-to-one correspondence.
  • Writing only the table name means adding the data of all fields, and the order should be the same as the field order when the table was created.
  • The quantity and data type must correspond.
  • insert语句一旦执行成功,必然会多一条记录,未指定值的字段默认为NULL。
mysql> insert into t_stu values(1,'zhangsan',21,'[email protected]','1999-9-9');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t_stu(num,name,age,birth,email) values(2,'lisi',21,'1999-10-10','[email protected]');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t_stu(num) values(3);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu;
+------+----------+------+------------------+------------+
| num  | name     | age  | email            | birth      |
+------+----------+------+------------------+------------+
|    1 | zhangsan |   21 | zhangsan@163.com | 1999-09-09 |
|    2 | lisi     |   21 | lisi@163.com     | 1999-10-10 |
|    3 | NULL     | NULL | NULL             | NULL       |
+------+----------+------+------------------+------------+
3 rows in set (0.00 sec)
4. Insert Date

4.1 mysql date format:

  • %Y years
  • %m month
  • %d days
  • %h hour
  • % i minutes
  • %s seconds

4.2 Date conversion function

  • str_to_date: Convert an abnormal date string into a date type, usually used in insert statements.
mysql> insert into user values(1,'zhangsan',str_to_date('01-01-1995','%d-%m-%Y'));
Query OK, 1 row affected (0.01 sec)
  • date_format: Format the date, convert the date into a string with a specific format, usually used in select statements to set the date format for display.
mysql> select id,name,date_format(birth,'%m/%d/%Y') birth from user;
+------+----------+------------+
| id   | name     | birth      |
+------+----------+------------+
|    1 | zhangsan | 01/01/1995 |
|    2 | lisi     | 03/03/1996 |
+------+----------+------------+
2 rows in set (0.00 sec)

4.3 The difference between date and datetime

mysql> insert into user values (1,'zhangsan','1999-09-09','2021-03-05 20:58:10');
Query OK, 1 row affected (0.01 sec)

mysql> insert into user values(2,'lisi','1999-10-10',now());
Query OK, 1 row affected (0.01 sec)

mysql> select * from user;
+------+----------+------------+---------------------+
| id   | name     | birth      | create_time         |
+------+----------+------------+---------------------+
|    1 | zhangsan | 1999-09-09 | 2021-03-05 20:58:10 |
|    2 | lisi     | 1999-10-10 | 2021-03-05 20:59:51 |
+------+----------+------------+---------------------+
2 rows in set (0.00 sec)

: now()You can get the current system time, accurate to the second.

4.4 Insert query results into the table

insert into 表1 select 字段 from 表2;
5. Quickly create a table (copy table structure and data)
create table 新表 as select * from 原表;
6. Modify table data (DML)
update 表名 set 字段1=值1,字段2=值2,... where 条件;

: No conditions will cause all data to be updated.

mysql> update user set name='jack',birth='2000-10-10' where id=2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from user;
+------+----------+------------+---------------------+
| id   | name     | birth      | create_time         |
+------+----------+------------+---------------------+
|    1 | zhangsan | 1999-09-09 | 2021-03-05 20:58:10 |
|    2 | jack     | 2000-10-10 | 2021-03-05 20:59:51 |
+------+----------+------------+---------------------+
2 rows in set (0.01 sec)
6. Delete table data

6.1 delete (DML)

delete from 表名 where 条件;

  • 没有条件Limit, the entire table data will be 全部删除! ! ! The table still exists.
  • Use delete to delete table data, the data on the hard disk 真实存储空间不会被释放.
  • Disadvantages: the deletion efficiency is low.
  • Advantages:, the 支持事务回滚deletion of errors can be restored.

6.2 truncate (DDL)

truncate table 表名;

  • You cannot delete a single piece of data.
  • Physically deleted, the table is truncated once. High efficiency, but does not support rollback.
  • Before using, carefully confirm whether the data can be deleted 删除后不可恢复.

Two, modify the table structure

Three, the deletion of the table

grammar:

drop table 表名;	//如果表不存在会报错

drop table if exists 表名;//表存在才删除,不存在什么都不做。

4. Constraints (Key Points)

1. What are constraints?

Constraint keywords: constraint
When creating a table, you can add some constraints to the fields in the table 保证表中数据的完整性和有效性.

  • Column-level constraint: For which column needs to add a constraint, just write the constraint name directly after the column.
  • Table-level constraints: The constraint is not added after the column, and it is used when multiple fields are combined and constraints. format:约束名(字段1,字段2,...)
2. Classification of constraints
Constraint name meaning
not null Non-null constraint, the field data cannot be NULL
unique Unique constraint, the data of this field is unique and cannot be repeated
primary key Primary key constraint, the field data is unique
foreign key Foreign key constraint
check Check constraints, mysql does not support, oracle support

2.1 not null Non-empty constraints

  • Non-null constraint fields must pass values ​​and cannot pass null. Not null has only column-level constraints.
mysql> create table vip(
    -> id int,
    -> name varchar(10) not null);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into vip values (1,'zhangsan');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip(id) values (3);
ERROR 1364 (HY000): Field 'name' doesn't have a default value
mysql> insert into vip values (3,null);
ERROR 1048 (23000): Column 'name' cannot be null

2.2 unique Unique constraint

  • The unique constraint field cannot be repeated, but it can be NULL, and there can be multiple NULLs.
mysql> create table vip(
    -> id int,
    -> name varchar(10) not null,
    -> email varchar(255) unique);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into vip values(1,'zhangsan','[email protected]');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(2,'lisi',null);
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(3,'wangwu','[email protected]');
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'vip.email'
  • Multiple fields are combined and unique, and multiple fields are regarded as a whole, all the same as the same, and the same part can still be inserted.
mysql> create table vip(
    -> id int,
    -> name varchar(10) not null,
    -> email varchar(255),
    -> unique(name,email));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into vip values(1,'zhangsan','[email protected]');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(2,'zhangsan','[email protected]');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(3,'zhangsan','[email protected]');
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'vip.name'

2.3 primary key Primary key constraint (PK for short)

  • Primary key uniquely identify each row is recorded 一张表只能有一个主键.
  • Any table should have a primary key. Without a primary key, the table is invalid!
mysql> create table vip(
    -> id int primary key,
    -> name varchar(10));
Query OK, 0 rows affected (0.02 sec)
  • The characteristics of the primary key: not null + unique ( 主键值不能为空且不能重复)
mysql> insert into vip values(1,'zs');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(2,'ls');
Query OK, 1 row affected (0.01 sec)

mysql> insert into vip values(2,'ww');
ERROR 1062 (23000): Duplicate entry '2' for key 'vip.PRIMARY'
mysql> insert into vip(name) values('zl');
ERROR 1364 (HY000): Field 'id' doesn't have a default value
  • Primary keys can be added using column-level constraints or table-level constraints.
mysql> create table vip(
    -> id int,
    -> name varchar(10),
    -> primary key(id));
Query OK, 0 rows affected (0.03 sec)
  • Multiple fields can be combined to add a primary key, which is called a composite primary key, and it is not recommended.
mysql> create table vip(
    -> id int,
    -> name varchar(10),
    -> primary key(id,name));
Query OK, 0 rows affected (0.03 sec)
  • In addition to a single primary key and a composite primary key, the primary key can also be divided into a natural primary key and a business primary key.
    Natural primary key: The primary key value is a natural number and has nothing to do with business.
    Business primary key: The primary key value is closely related to the business, for example, the bank card number is used as the primary key value.
    In actual development, natural primary keys are used more, because the primary keys only need to be non-repetitive, which is meaningless. Using the business primary key, it is unlikely that the primary key value will be affected when the business changes.
  • In mysql, you can use the auto_incrementautomatic maintenance of the primary key value, which means that 自增it starts from 1 and increments by 1.

2.4 foreign key Foreign key constraints (FK for short)

In order to avoid data redundancy and space waste, foreign keys can be added to ensure the validity of the data.

create table 表名(
	字段 数据类型 foreign key(外键字段名) references 引用表(引用字段名)
	);

  • The table to which the foreign key is added is called the child table, and the referenced table is called the parent table.
  • The order in which the tables are created? Create the parent table first, and then create the child table.
  • The order of inserting data? Insert the parent table first, and then insert the child table.
  • The order of deleting tables and table data? First delete the child table, then delete the parent table.

To be continued

Guess you like

Origin blog.csdn.net/zhengrong9/article/details/114411369