Mysql basics - DDL, DML, DQL, DCL, functions, constraints

MySQL basics

1. Data model

1.1 Relational database and non-relational database

  • relational database (RDBMS)

    Concept : Based on the relational model, it is a database composed of two-dimensional tables connected to each other .

Mysql database is a relational database

​Two-dimensional table :

​ Use tables to store data, the format is uniform, and it is easy to maintain

​ Use SQL language operation, unified standard, easy to use

image-20230521110341537

  • non-relational database

​ A database that does not store data through a table structure.

For example, Redis is a non-relational database

1.2 Mysql data model

​ After installing MySQL, our computer becomes a Mysql database server, we can connect to the Mysql database management system DBMS through the client, and then use SQL statements to create a database through the database management system, or through the database management system to specify Create tables in the database

image-20230521111429940

name full name Abbreviation
database A warehouse for storing data, where data is stored in an organized manner DataBase(DB)
database management system large software for manipulating and managing databases DataBase Management System (DBMS)
SQL A programming language for operating relational databases, which defines a set of operations Structured Query Language (SQL)

Two, SQL

2.1 SQL general syntax

  • SQL statements can be written in one or more lines, ending with a semicolon

  • SQL statements can use spaces/indentation to enhance statement readability

  • The SQL statement of the MySQL database is not case-sensitive, and it is recommended to use capital letters for keywords

  • Single-line comment: -- comment content or # comment content

  • Multi-line comments: / comment content /

2.2 SQL classification

Classification full name illustrate
DDL Data Definition Language Data Definition Language, used to define database objects (databases, tables, fields)
DML Data Manipulation Language Data manipulation language, used to add, delete, and modify data in database tables
DQL Data Query Language Data query language, used to query the records of tables in the database
DCL Data Control Language Data control language, used to create database users, control database

2.3 DDL

​Concept : Data Definition Language, data definition language, used to **define database objects (databases, tables, fields)**.

2.3.1 Database operation

  • query all databases

show databases ;
  • Query the current database
select database() ;
  • create database
create database [ if not exists ] 数据库名 [ default charset 字符集 ] [ collate 排序
规则 ] ;

​ It is not recommended to set the character set of the database to UTF-8, because the storage length of UTF-8 Chinese characters is three bytes, but some special characters in the database occupy four bytes, so it is recommended four bytes

  • delete
DROP DATABASE [if exists] 数据库名;
  • use
USE 数据库名;

2.3.2 Table Operation - Create & Query

  • Query all tables in the current database
show tables;
  • View the specified table structure
desc 表名 ;

​ You can view the fields of the specified table, the type of the field, whether it can be NULL, whether there is a default value, etc.

image-20230521140004198

  • Query the table creation statement of the specified table
show create table 表名 ;

​ Through this command, it is mainly used to view the table creation statement, and some parameters will be queried when we create the table without specifying, because this part is the default value of the database, such as: storage engine, character set etc.

CREATE TABLE dept(
idint unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key\r\nID',
namevarchar(10) NOT NULL COMMENT 'department name',
create_timedatetime NOT NULL COMMENT 'creation time',
update_timedatetime NOT NULL COMMENT 'modification time',
PRIMARY KEY ( id),
UNIQUE KEY name( name)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='department table'

image-20230521140039094

  • create table
CREATE TABLE 表名(
字段1 字段1类型 [ COMMENT 字段1注释 ],
字段2 字段2类型 [COMMENT 字段2注释 ],
字段3 字段3类型 [COMMENT 字段3注释 ],
......
字段n 字段n类型 [COMMENT 字段n注释 ]
) [ COMMENT 表注释 ] ;

No comma after the last field

create table if not exists tb_user(
     id     int         COMMENT '编号',
	 name   varchar(50) COMMENT '姓名',
	 age    int         COMMENT '年龄',
	 gender varchar(1)  COMMENT '性别'

) comment '用户表';

image-20230521140811004

2.3.3 Table operation - modify & delete

  • add field

ALTER TABLE 表名 ADD 字段名 类型 (长度) [ COMMENT 注释 ] [ 约束 ];

Add a new field "nickname" to the emp table as nickname, and the type is varchar(20)

ALTER TABLE emp ADD nickname varchar(20) COMMENT '昵称';
  • modify data type
ALTER TABLE 表名 MODIFY 字段名 新数据类型 (长度);
  • Modify field names and types
ALTER TABLE 表名 CHANGE 旧字段名 新字段名 类型 (长度) [ COMMENT 注释 ] [ 约束 ];
ALTER TABLE emp CHANGE nickname username varchar(30) COMMENT '昵称';
  • delete field

    ALTER TABLE 表名 DROP 字段名;
    

    Delete the field username of the emp table

    ALTER TABLE emp DROP username;
    
  • modify table name

ALTER TABLE 表名 RENAME TO 新表名;
  • delete table
DROP TABLE [ IF EXISTS ] 表名;

When deleting a table, all data in the table will also be deleted.

  • Drop the specified table and recreate it
TRUNCATE TABLE 表名;

truncate: truncation, interception

When deleting a table, all data in the table will also be deleted.

2.3.4 Data Types

Three types : numeric type, string type, date and time type.

2.3.4.1 Numeric types

TINYINT is similar to byte in Java language, occupying 1 byte

SMALLINT is similar to short in the Java language, occupying 2 bytes

INT/INTEGER is similar to int in Java language, occupying 4 bytes

BIGINT is similar to long in the Java language, occupying 8 bytes

The first five are integers, and the last three are floating-point

FLOAT is similar to float in the Java language, occupying 4 bytes

DOUBLE is similar to the double type in the Java language, occupying 8 bytes

type size signed (SIGNED) range Unsigned (UNSIGNED) range describe
TINYINT 1 byte (-128,127) (0,255) small integer value
SMALLINT 2 bytes (-32768,32767) (0,65535) big integer value
MEDIUMINT 3bytes (-8388608,8388607) (0,16777215) big integer value
INT/INTEGER 4bytes (-2147483648,2147483647) (0,4294967295) big integer value
BIGINT 8bytes (-263,263-1) (0,2^64-1) extremely large integer value
FLOAT 4bytes (-3.402823466 E+38,3.402823466351 E+38) 0 sum (1.175494351 E-38, 3.402823466 E+38) single precision floating point
DOUBLE 8bytes (-1.7976931348623157E+308,1.7976931348623157E+308) 0 and (2.2250738585072014E-308, 1.7976931348623157E+308) double-precision floating-point value
DECIMAL Depends on the values ​​of M (precision) and D (scale) Depends on the values ​​of M (precision) and D (scale) Decimal value (exact point number)

What are precision and scale?

Such as 123.45, the precision is the entire length 5, and the scale is the number of digits after the decimal point 2

What does score double(4,1) mean?

The precision of the score field is 4 (100.0), with only one decimal place

How to use unsigned range?

age tinyint unsigned means the range of the age field is (0, 255)

2.3.4.2 String type

type size describe
CHAR 0-255 bytes Fixed-length string (need to specify the length)
VARCHAR 0-65535 bytes Variable-length string (need to specify the length)
TINYBLOB 0-255 bytes Binary data not exceeding 255 characters
TINYTEXT 0-255 bytes short text string
BLOB 0-65 535 bytes Long text data in binary form
TEXT 0-65 535 bytes long text data
MEDIUMBLOB 0-16 777 215 bytes Medium-length text data in binary form
MEDIUMTEXT 0-16 777 215 bytes medium length text data
LUNG BLOB 0-4 294 967 295 bytes Very large text data in binary form
LONGTEXT 0-4 294 967 295 bytes extremely large text data

The difference between char and varchar?

​ Both char and varchar can describe strings, char is a fixed-length string, and the specified length will occupy as many characters as it takes, regardless of the length of the field value. And varchar is a variable-length string, and the specified length is the maximum occupied length. ** Relatively speaking, the performance of char will be higher. **Because varchar will calculate the storage space size according to the content when storing, so the performance is lower

  • Username username ------> The length is variable, the longest will not exceed 50

​ username varchar(50)

  • Gender ---------> storage value, either male or female

​ gender char(1)

  • Mobile phone number phone --------> Fixed length is 11

​ phone char(11)

2.3.4.3 Datetime type

DATE, TIME, DATETIME will be used more

type size scope Format describe
DATE 3 1000-01-01 to 9999-12-31 YYYY-MM-DD date value
TIME 3 -838:59:59 to 838:59:59 HH:MM:SS time value or duration
YEAR 1 1901 to 2155 YYYY year value
DATETIME 8 1000-01-01 00:00:00 to 9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS Mixed date and time values
TIMESTAMP 4 1970-01-01 00:00:01 to 2038-01-19 03:14:07 YYYY-MM-DD HH:MM:SS 混合日期和时间值,时间戳

2.3.4.4 总结案例

设计一张员工信息表,要求如下:

  1. 编号(纯数字)

  2. 员工工号 (字符串类型,长度不超过10位)

  3. 员工姓名(字符串类型,长度不超过10位)

  4. 性别(男/女,存储一个汉字)

  5. 年龄(正常人年龄,不可能存储负数)

  6. 身份证号(二代身份证号均为18位,身份证中有X这样的字符)

  7. 入职时间(取值年月日即可)

create table emp(
id int comment '编号',
workno varchar(10) comment '工号',
name varchar(10) comment '姓名',
gender char(1) comment '性别',
age tinyint unsigned comment '年龄',
idcard char(18) comment '身份证号',
entrydate date comment '入职时间'
) comment '员工表';

2.4 DML

​ DML英文全称是Data Manipulation Language(数据操作语言),用来对数据库中表的数据记录进行增、删、改操作

  • 添加数据(INSERT)
  • 修改数据(UPDATE)
  • 删除数据(DELETE)

2.4.1 插入数据

  • 指定字段添加数据
INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (1,2, ...); 1

比如:

insert into employee(id,workno,name,gender,age,idcard,entrydate)
values(1,'1','Itcast','男',10,'123456789012345678','2000-01-01');
  • 给全部字段添加数据
INSERT INTO 表名 VALUES (1,2, ...);

但是数据的字段一定要进行对应

insert into employee values(2,'2','张无忌','男',18,'123456789012345670','2005-01-01');
  • 批量添加数据
INSERT INTO 表名 (字段名1, 字段名2, ...)
VALUES (1,2, ...), 
       (1,2, ...), 
       (1,2, ...) ;

或者

INSERT INTO 表名 
VALUES (1,2, ...), 
       (1,2, ...), 
       (1,2, ...) ;

案例

insert into employee 
values(3,'3','韦一笑','男',38,'123456789012345670','2005-01-01'),
      (4,'4','赵敏','女',18,'123456789012345670','2005-01-01');

注意事项

  • 插入数据时,指定的字段顺序需要与值的顺序是一一对应的。
  • 字符串和日期型数据应该包含在引号中。
  • 插入的数据大小,应该在字段的规定范围内。

2.4.2 更新数据

语法

UPDATE 表名 SET 字段名1 =1 , 字段名2 =2 , .... [ WHERE 条件 ] ;

案例

  • 修改id为1的数据,将name修改为itheima
update employee set name = 'itheima' where id = 1;
  • 修改id为1的数据, 将name修改为小昭, gender修改为 女
update employee set name = '小昭' , gender = '女' where id = 1;
  • 将所有的员工入职日期修改为 2008-01-01
update employee set entrydate = '2008-01-01';

注意

​ 修改语句的条件可以有,也可以没有,如果没有条件,则会修改整张表的所有数据。

2.4.3 删除数据

语法

DELETE FROM 表名 [ WHERE 条件 ] ;
  • 删除gender为女的员工
delete from employee where gender = '女';
  • 删除所有员工
delete from employee;

注意事项

  • DELETE 语句的条件可以有,也可以没有,如果没有条件,则会删除整张表的所有数据。
  • DELETE 语句不能删除某一个字段的值(可以使用UPDATE,将该字段值置为NULL即可)
  • 当进行删除全部数据操作时,datagrip会提示我们,询问是否确认删除,我们直接点击Execute即可。

2.5 DQL

​ DQL英文全称是Data Query Language(数据查询语言),数据查询语言,用来查询数据库中表的记录。

2.5.1 数据准备

drop table if exists employee;

create table emp(
  id int comment '编号',
  workno varchar(10) comment '工号',
  name varchar(10) comment '姓名',
  gender char(1) comment '性别',
  age tinyint unsigned comment '年龄',
  idcard char(18) comment '身份证号',
  workaddress varchar(50) comment '工作地址',
  entrydate date comment '入职时间'
)comment '员工表';


INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (1, '00001', '柳岩666', '女', 20, '123456789012345678', '北京', '2000-01-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (2, '00002', '张无忌', '男', 18, '123456789012345670', '北京', '2005-09-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (3, '00003', '韦一笑', '男', 38, '123456789712345670', '上海', '2005-08-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (4, '00004', '赵敏', '女', 18, '123456757123845670', '北京', '2009-12-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (5, '00005', '小昭', '女', 16, '123456769012345678', '上海', '2007-07-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (6, '00006', '杨逍', '男', 28, '12345678931234567X', '北京', '2006-01-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (7, '00007', '范瑶', '男', 40, '123456789212345670', '北京', '2005-05-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (8, '00008', '黛绮丝', '女', 38, '123456157123645670', '天津', '2015-05-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (9, '00009', '范凉凉', '女', 45, '123156789012345678', '北京', '2010-04-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (10, '00010', '陈友谅', '男', 53, '123456789012345670', '上海', '2011-01-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (11, '00011', '张士诚', '男', 55, '123567897123465670', '江苏', '2015-05-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (12, '00012', '常遇春', '男', 32, '123446757152345670', '北京', '2004-02-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (13, '00013', '张三丰', '男', 88, '123656789012345678', '江苏', '2020-11-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (14, '00014', '灭绝', '女', 65, '123456719012345670', '西安', '2019-05-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (15, '00015', '胡青牛', '男', 70, '12345674971234567X', '西安', '2018-04-01');

INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate)
VALUES (16, '00016', '周芷若', '女', 18, null, '北京', '2012-06-01');

2.5.2 基本语法

SELECT
  字段列表
FROM
  表名列表
WHERE
  条件列表
GROUP BY
  分组字段列表
HAVING
  分组后条件列表
ORDER BY
  排序字段列表
LIMIT
  分页参数
  • 基本查询(不带任何条件)
  • 条件查询(WHERE)
  • 聚合函数(count、max、min、avg、sum)
  • 分组查询(group by)
  • 排序查询(order by)
  • 分页查询(limit)

2.5.3 基础查询

  • 查询多个字段
SELECT 字段1, 字段2, 字段3 ... 
FROM 表名 ;
SELECT * 
FROM 表名 ;

注意 * 号代表查询所有字段,在实际开发中尽量少用(不直观、影响效率)。

案例

select id,workno,name,gender,age,idcard,workaddress,entrydate 
from emp;
  • 字段设置别名
SELECT 字段1 [ AS 别名1 ] , 字段2 [ AS 别名2 ] ... 
FROM 表名;
SELECT 字段1 [ 别名1 ] , 字段2 [ 别名2 ] ... 
FROM 表名;

案例

select workaddress as '工作地址' 
from emp;
select workaddress '工作地址' 
from emp;
  • 去除重复记录
SELECT DISTINCT 字段列表 
FROM 表名;
select distinct workaddress '工作地址'
from emp;

2.5.4 条件查询

语法

SELECT 字段列表 FROM 表名 
WHERE 条件列表 ;

常见比较运算符条件

比较运算符 功能
> 大于
>= 大于等于
< 小于
<= 小于等于
= 等于
<> 或 != 不等于
BETWEEN … AND … 在某个范围之内(含最小、最大值)
IN(…) 在in之后的列表中的值,多选一
LIKE 占位符 模糊匹配(_匹配单个字符, %匹配任意个字符)
IS NULL 是NULL

常见逻辑运算符

逻辑运算符 功能
AND 或 && 并且 (多个条件同时成立)
OR 或 || 或者 (多个条件任意一个成立)
NOT 或 ! 非 , 不是

案例

  • 查询年龄等于18 或 20 或 40 的员工信息
select *
from emp 
where age = 18 or age = 20 or age =40;

select * 
from emp 
where age in(18,20,40);
  • 查询姓名为两个字的员工信息
select * 
from emp 
where name like '__';
  • 查询身份证号最后一位是X的员工信息
select * 
from emp 
where idcard like '%X';

select * 
from emp 
where idcard like '_________________X';

2.5.4 聚合函数

将一列数据作为一个整体,进行纵向计算

语法

SELECT 聚合函数(字段列表) 
FROM 表名 ;

NULL值是不参与所有聚合函数运算!!!

常见的聚合函数

函数 功能
count 统计数量
max 最大值
min 最小值
avg 平均值
sum 求和

案例

  • 统计该企业员工数量
-- 统计的是总记录数,null也统计
select count(*) from emp; 

-- 统计的是idcard字段不为null的记录数
select count(idcard) from emp; 

下面等同于select count(*) from emp;

select count(1) from emp; 

​ "count(1)“是SQL查询语句中的一种写法,用于对一张表进行计数。它的作用是统计表中所有的行数,可以用来查询表中数据的总量。与其等价的写法是"count(*)”,它也可以用来计数。不同的数据库系统在使用count函数时可能存在些许差异,但通常都支持这两种写法。

2.5.5 分组查询

语法

SELECT 字段列表 
FROM 表名 [ WHERE 条件 ] 
GROUP BY 分组字段名 
[HAVING 分组后过滤条件 ];

where与having区别?

  • 执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组之后对结果进行过滤。

  • 判断条件不同:where不能对聚合函数进行判断,而having可以。

注意事项

  • 分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义。

  • 执行顺序: where > 聚合函数 > having 。

  • 支持多字段分组, 具体语法为 : group by columnA,columnB

案例

  • 根据性别分组 , 统计男性员工 和 女性员工的数量
select gender, count(*)
from emp
group by gender ;
  • 根据性别分组 , 统计男性员工 和 女性员工的平均年龄
select gender, avg(age) 
from emp 
group by gender ;
  • 查询年龄小于45的员工 , 并根据工作地址分组 , 获取员工数量大于等于3的工作地址
select workaddress, count(*) address_count 
from emp 
where age < 45 
group by workaddress 
having address_count >= 3;
  • 统计各个工作地址上班的男性及女性员工的数量
select workaddress, gender, count(*) '数量' 
from emp 
group by gender , workaddress;

2.5.6 排序查询

排序在日常开发中是非常常见的一个操作,有升序排序,也有降序排序。

语法

SELECT 字段列表 
FROM 表名 
ORDER BY 字段1 排序方式1 , 字段2 排序方式2 ;

排序方式

  • ASC : 升序(默认值),从小到大
  • DESC: 降序,从大到小

注意事项

  • 如果是升序, 可以不指定排序方式ASC ;

  • 如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序 ;

案例

  • 根据年龄对公司的员工进行升序排序
select * from emp order by age asc;

select * from emp order by age;
  • 根据年龄对公司的员工进行升序排序 , 年龄相同 , 再按照入职时间进行降序排序
select * 
from emp 
order by age asc , entrydate desc;

2.5.7 分页查询

分页操作在业务系统开发时,也是非常常见的一个功能,我们在网站中看到的各种各样的分页条,后台都需要借助于数据库的分页操作。

语法

SELECT 字段列表 FROM 表名 LIMIT 起始索引, 查询记录数 ;

注意事项:

  • 起始索引从0开始,起始索引 = (查询页码 - 1)* 每页显示记录数。

  • 分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是LIMIT。

  • 如果查询的是第一页数据,起始索引可以省略,直接简写为 limit 10。

案例

  • 查询第1页员工数据, 每页展示10条记录
select * from emp limit 0,10;
select * from emp limit 10;
  • 查询第2页员工数据, 每页展示10条记录 --------> (页码-1)*页展示记录数
select * from emp limit 10,10;

2.5.8 执行顺序

image-20230521183907907

2.6 DCL

​ DCL英文全称是Data Control Language(数据控制语言),用来管理数据库用户、控制数据库的访问权限。

2.6.1 管理用户

  • 查询用户
select * 
from mysql.user;

或者

use mysql;

select * 
from user;

image-20230521185226639

​ 其中 Host代表当前用户访问的主机, 如果为localhost, 仅代表只能够在当前本机访问,是不可以远程访问的。 User代表的是访问该数据库的用户名。

​ 在MySQL中需要通过Host和User来唯一标识一个用户。

  • 创建用户
CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码';

​ 仅仅是创建了用户,并没有权限访问其他数据库

创建用户itcast, 只能够在当前主机localhost访问, 密码123456

create user 'itcast'@'localhost' identified by '123456'; 

创建用户heima, 可以在任意主机访问该数据库, 密码123456

create user 'heima'@'%' identified by '123456';
  • 修改用户密码
ALTER USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '新密码' ;

修改用户heima的访问密码为1234

alter user 'heima'@'%' identified with mysql_native_password by '1234';
  • 删除用户

    DROP USER '用户名'@'主机名' ;
    

删除 itcast@localhost 用户

drop user 'itcast'@'localhost';

注意事项

  • 在MySQL中需要通过用户名@主机名的方式,来唯一标识一个户。
  • 主机名可以使用 % 通配。
  • 这类SQL开发人员操作的比较少,主要是DBA( Database Administrator 数据库管理员)使用。

2.6.2 权限控制

权限官方文档MySQL :: MySQL 8.0 Reference Manual :: 6.2.2 Privileges Provided by MySQL

常用权限

权限 说明
ALL, ALL PRIVILEGES 所有权限
SELECT 查询数据
INSERT 插入数据
UPDATE 修改数据
DELETE 删除数据
ALTER ALTER
DROP 删除数据库/表/视图
CREATE 创建数据库/表
  • 查询权限
SHOW GRANTS FOR '用户名'@'主机名' ;
show grants for 'heima'@'%';
  • 授予权限
GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'主机名';

授予 ‘heima’@‘%’ 用户itcast数据库所有表的所有操作权限

grant all on itcast.* to 'heima'@'%';
  • 撤销权限
REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'主机名';
revoke all on itcast.* from 'heima'@'%';

注意事项

  • 多个权限之间,使用逗号分隔

  • 授权时, 数据库名和表名可以使用 * 进行通配,代表所有。

三、函数

函数 是指一段可以直接被另一段程序调用的程序或代码

四类: 字符串函数、数值函数、日期函数、流程函数

3.1 字符串函数

函数 功能
CONCAT(S1,S2,…Sn) 字符串拼接,将S1,S2,… Sn拼接成一个字符串
LOWER(str) 将字符串str全部转为小写
UPPER(str) 将字符串str全部转为大写
LPAD(str,n,pad) 左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
RPAD(str,n,pad) 右填充,用字符串pad对str的右边进行填充,达到n个字符串长度
TRIM(str) 去掉字符串头部和尾部的空格
SUBSTRING(str,start,len) 返回从字符串str从start位置起的len个长度的字符串
  • concat :字符串拼接
select concat('hello','Mysql')

结果:helloMysql

  • lower:全部转小写
SELECT LOWER('Hello')

结果:hello

  • upper : 全部转大写
SELECT UPPER('Hello')

结果:HELLO

  • lpad : 左填充
SELECT LPAD('Hello',10,'Mysql')

结果:MysqlHello

  • rpad : 右填充
SELECT rpad('Hello',10,'Mysql')

结果:HelloMysql

  • trim : 去除头尾空格
select trim(' Hello MySQL ');

结果:Hello MySQL

  • substring : 截取子字符串
select substring('Hello MySQL',1,5);

结果:Hello

案例

由于业务需求变更,企业员工的工号统一为5位数,目前不足五位数的全部在前面补0.

update emp set workno = lpad(workno, 5, '0');

3.2 数值函数

函数 功能
CEIL(x) 向上取整
FLOOR(x) 向下取整
MOD(x,y) 返回x/y的模
RAND() 返回0~1内的随机数
ROUND(x,y) 求参数x的四舍五入的值,保留y位小数

案例

通过数据库的函数,生成一个六位数的随机验证码。

SELECT  lpad(floor(rand()*1000000) ,6,'0')
select lpad(round(rand()*1000000 , 0), 6, '0');

3.3 日期函数

函数 功能
CURDATE() 返回当前日期
CURTIME() 返回当前时间
NOW() 返回当前日期和时间
YEAR(date) 获取指定date的年份
MONTH(date) 获取指定date的月份
DAY(date) 获取指定date的日期
DATE_ADD(date, INTERVAL exprtype) 返回一个日期/时间值加上一个时间间隔expr后的时间值
DATEDIFF(date1,date2) 返回起始时间date1 和 结束时间date2之间的天(date1-date2)
  • date_add:增加指定的时间间隔
select date_add(now(), INTERVAL 70 YEAR );

select date_add(now(), INTERVAL 70 MONTH );

select date_add(now(), INTERVAL 70 DAY );
  • datediff:获取两个日期相差的天数
-- -61
select datediff('2021-10-01', '2021-12-01');

案例

​ 查询所有员工的入职天数,并根据入职天数倒序排序。

ELECT name , datediff(now(),entrydate) as date
from emp
ORDER BY date DESC

select name, datediff(curdate(), entrydate) as 'entrydays' 
from emp 
order by entrydays desc;

3.4 流程函数

可以在SQL语句中实现条件筛选,从而提高语句的效率。

函数 功能
IF(value , t , f) 如果value为true,则返回t,否则返回f
IFNULL(value1 , value2) 如果value1不为空,返回value1,否则返回value2
CASE WHEN [ val1 ] THEN [res1] … ELSE [ default ] END 如果val1为true,返回res1,… 否则返回default默认值
CASE [ expr ] WHEN [ val1 ] THEN [res1] … ELSE [ default ] END 如果expr的值等于val1,返回res1,… 否则返回default默认值
  • case when then else end

需求:

​ 查询emp表的员工姓名和工作地址 (北京/上海 ----> 一线城市 , 其他 ----> 二线城市)

select
   name,
  ( case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end ) as '工作地址'
	
from emp;

四、约束

4.1 分类

概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。

目的:保证数据库中数据的正确、有效性和完整性。

约束 描述 关键字
非空约束 限制该字段的数据不能为null NOT NULL
唯一约束 保证该字段的所有数据都是唯一、不重复的 UNIQUE
主键约束 The primary key is the unique identifier of a row of data, which requires non-null and unique PRIMARY KEY
default constraint When saving data, if the value of this field is not specified, the default value will be used DEFAULT
Check constraints (after version 8.0.16) Ensure that the field value satisfies a certain condition CHECK
foreign key constraints It is used to establish a connection between the data of the two tables to ensure the consistency and integrity of the data FOREIGN KEY

Notice

约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束。

4.2 Constraint Demonstration

image-20230522101709164

create table tb_user(
  id     int          PRIMARY KEY AUTO_INCREMENT  COMMENT 'ID唯一标识',
	
	name   varchar(10)  NOT NULL UNIQUE             COMMENT '姓名',
	
	age    int          CHECK  (0<age&& age<=120)   COMMENT '年龄',
	
	status char(1)      DEFAULT(1)                  COMMENT '状态',
	
	gender char(1)                                  COMMENT '状态'

);

4.3 Foreign key constraints

Foreign key : It is used to establish a connection between the data of the two tables, so as to ensure the consistency and integrity of the data.

4.3.1 Prepare data

create table dept(

  id int auto_increment comment 'ID' primary key,

  name varchar(50) not null comment '部门名称'

)comment '部门表';


INSERT INTO dept (id, name) VALUES (1, '研发部'), (2, '市场部'),(3, '财务部'), (4,'销售部'), (5, '总经办');

create table emp(
  id int auto_increment comment 'ID' primary key,
  name varchar(50) not null comment '姓名',
  age int comment '年龄',
  job varchar(20) comment '职位',
  salary int comment '薪资',
  entrydate date comment '入职时间',
  managerid int comment '直属领导ID',
  dept_id int comment '部门ID'
)comment '员工表';


INSERT INTO emp (id, name, age, job,salary, entrydate, managerid, dept_id)
VALUES
(1, '金庸', 66, '总裁',20000, '2000-01-01', null,5),(2, '张无忌', 20,'项目经理',12500, '2005-12-05', 1,1),
(3, '杨逍', 33, '开发', 8400,'2000-11-03', 2,1),(4, '韦一笑', 48, '开发',11000, '2002-02-05', 2,1),
(5, '常遇春', 43, '开发',10500, '2004-09-07', 3,1),(6, '小昭', 19, '程序员鼓励师',6600, '2004-10-12', 2,1);

image-20230522103445309

4.3.2 Syntax

  • add foreign key
CREATE TABLE 表名(
字段名 数据类型,
    
...
    
[CONSTRAINT] [外键名称] FOREIGN KEY (外键字段名) REFERENCES 主表 (主表列名)
);
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表 (主表列名) ;
  • delete foreign key
ALTER TABLE 表名 DROP FOREIGN KEY 外键名称;

4.3.3 Delete/Update Behavior

After adding a foreign key, the constraint behavior generated when deleting the parent table data is called delete/update behavior. The specific delete/update behaviors are as follows

Behavior illustrate
NO ACTION When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with RESTRICT) default behavior
RESTRICT When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with NO ACTION) default behavior
CASCADE When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update the record in the child table with the foreign key.
SET NULL When deleting the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, set the value of the foreign key in the child table to null (this requires that the foreign key allows null).
SET DEFAULT When the parent table is changed, the child table sets the foreign key column to a default value (Innodb does not support)

Concrete grammar

set behavior to CASCADE

ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 主表名 (主表字段名) ON UPDATE CASCADE ON DELETE CASCADE;

Guess you like

Origin blog.csdn.net/weixin_51351637/article/details/130863414