SQL overview and MySQL common statement summary

Database overview

Why use a database to store data instead of directly storing it in files of various formats? For example, if you want to store name='zs', age=20, you can use the database to build a table to store it, and you can use a .txt file to store it?

  • Compared with 数据库管理系统directly operating files, the use of databases greatly improves data management efficiency, stores more data, ensures data consistency, completeness, and security while reducing data redundancy and facilitating data sharing.
  • For example, I want to query the ages of all persons named 'zs' in the above data, use java to operate the database, only need to write a SQL and use a fixed process to query, and use file storage, it may be necessary to obtain multiple files The IO stream reads data, traverses the data and makes judgments, etc., which is very troublesome and extremely inefficient. For thousands of data, it is simply a big difference.

Since database storage has so many advantages, why not use a database to store all text files? Or why not use a DBMS system instead of a file system?

  • Files support data in various formats, while databases have too many constraints on data
  • The database also depends on the file system
  • The reading of files does not require the participation of other middleware, and is more suitable for storing data that is relatively independent, has a small amount, various formats, and does not require frequent operations. For example, if you store the configuration information of a software in a file format, you can’t connect to the specified database to read the data when all the software starts, or build a data

Databases, database management systems, structured query languages ​​(DB, DBMS, SQL)

  • 数据库: A warehouse for storing data, which stores data in an organized manner
  • 数据库管理系统: Now that the warehouse has been specified, how to put data into the warehouse, and how to obtain data from the warehouse according to conditions? This requires a management 软件. Similar to Cainiao Station, the shelves of the entire station are used as warehouses, but a management system is required for receiving and taking out express delivery. Everyday databases such as Mysql, Oracle, etc. refer to database management systems.
  • 结构化查询语言: Structured Query Language, that is SQL, is 关系型数据库circulated between all through the database management system 操作数据库的编程语言. This is also a major advantage of relational databases. Different relational databases such as Oracle, MySQL, SQL Serveretc. can be operated using the language of SQL, and only a few small places need to be changed.
    insert image description here

Comparison of SQL and NoSQL

  • 数据结构化: Data storage in SQL is limited by borders, such as specified fields, specified data types, etc., while NoSQL is in a very loose format, such as redis key-value pair storage, which does not require the data structure of V
  • 数据关联性: There can be a relationship between SQL tables and tables, such as one-to-many, one-to-many, and many-to-many, and data consistency is usually considered. In NoSQL, each piece of data exists independently, and deleting this piece does not need to consider whether other data depends on this data.
  • 查询方式: There is a unified query language among SQL databases, while each NoSQL vendor has its own language
  • 存储方式: Most of the data to be operated by SQL is stored on the disk, while most of the data to be operated by NoSQL is stored in the memory, and the disk is used to store the backup data

insert image description here
Relational databases store data in the form of rows and columns, forming one 二维表. The biggest advantage is that it supports 复杂的查询, 方便维护,支持事务

Common examples of relational database management systems

Ranking by market share

  • Oracle: It was born in 1972 and became the first commercial database, suitable for 大型databases. Its company also changed its name to Oracle Corporation. In 2009, Sun (including MySQL) was acquired, so Oracle currently owns both Oracledatabase ( 收费) and MySQLdatabase ( 分为社区版和商业版).
  • MySQL: An open source 免费database, suitable for 中小型databases, developed in 1995, acquired by Sun in 2008, and acquired by Oracle in 2009, so it currently belongs to Oracle. Oracle divides MySQL into free community edition and paid commercial edition
  • SQL Server中型: Database launched by Microsoft , commonly used in C# and .NET
  • PostgreSQL: Open source free small and medium database
  • DB2: IBM's large-scale charging database product, often used in banks
  • SQLLite: Embedded micro-database, often used on mobile phones
  • MariaDB: An open source and free small and medium-sized database. The founder of MySQL worried about the risk of closed source after MySQL was acquired, so he created a MySQL branch project MariaDB, which has good compatibility with MySQL.

MySQL

introduce

  • MySQL currently belongs to Oraclethe company (it has been introduced in the past and present, so I won’t repeat it here).
  • It is an open source, free, and customizable database management system.
  • Support the management 千万条数据的of large databases, the largest table file support for 32-bit systems 4GB, and the largest table file support for 64-bit systems8TB
  • standardSQL数据语言
  • Allows to run on multiple systems, and supports multiple languages ​​such as: C, C++, Java, python, Php, Ruby, etc.
  • A milestone version was released in 2016 MySQL8.0, with significant enhancements in functionality

Advantages :

  1. Open source and free, low cost of use
  2. Good performance and stable service
  3. Small size, easy to use
  4. Established and active community

Install

The Win version and the Linux version are installed in different ways, and the installation takes version 8 as an example

For the win version, you only need to click the file and then click the next step. You can specify , , , msiduring installation . After installation, remember to configure environment variables so that you can use sql commands anywhere.连接的端口root用户密码服务名称是否自启动

linux version The downloaded package of the linux version needs to be decompressed, and then use rpm -ivhthe step-by-step installation of the files in the package, and finally start the MySQL service. systemctl start mysqldMySQL will have a password by default when it is first started. You need to query the default generated password in the startup log. grep 'temporary password' /var/log/mysqld.logAfter logging in as root, you need To modify the password, the default password of MySQL is strict mode, that is, there must be more than 8 digits with numbers and letters.
If you don’t want to do this, you can modify the global variables of MySQL.
For example, if you use weak mode, change the required password digits to greater than 4

set global validate_password.policy = 0;
set global validate_password.length = 4;

The default host name of the root user is localhost, which means that you can only use this machine to connect, that is, you cannot use other devices to log in and connect, and you need to modify the corresponding login ip of the user

update user set host='%' where user ='root'; 使用通配符% 改为了任意连接ip

After configuring all this, restart

database connection

  • 开启Database service: net start mysql80It will be started automatically during installation. If the service name remains unchanged, it is sql80. If you modify it, you need to use your own

  • 关闭Database Services: net stop mysql80
    Command Line

  • Enter in the cmd window: mysql [-h 主机地址] [-P 端口] -u 用户名(通常为root)-p (specify password mode): If the database is on the local machine and the port is not modified, the content in [] can be omitted. The password of -p is not directly filled in the command for safety, but enter the command and press Enter, and then enter the password
    insert image description here
    to connect to the client

  • sqlyog

insert image description here


  • Navicate: (personal favorite)
    insert image description here

  • dataGrip:

insert image description here
Idea's connection database plug-in can also be easily connected

insert image description here

SQL

SQL is a unified data language for structural databases. It defines a unified standard for operating relational databases. It is divided into four types according to different functions.

class name illustrate
DDL Database 定义语言, such as creating a library, modifying a library, deleting a library, creating a table, modifying a table (that is, modifying a field), deleting a table, etc. In short, it is to create a structural constraint and wait for the insertion of data
DML Data 操作语言, the operation on the data in the table 增、删、改will change the data in the structure
DQL Data 查询语言, perform various operations on the data in the table without changing the data.
DCL Data 权限控制语言, control certain permissions of data, and ensure the security of the data system

insert image description here

General syntax :

  • ;Use to separate multiple SQL statements
  • It is not sensitive to win版case, but Linux版大小写敏感(can be set), so develop according to case sensitivity, use keywords, function names, and variable names 大写; use database names, table names, and field names小写
阿里开发公约【强制】
表名、字段名必须使用小写字母或数字 , 
禁止出现数字开头,禁止两个下划线中间只 出现数字。
数据库字段名的修改代价很大,因为无法进行预发布,所以字段名称需要慎重考虑。
  • Notes:
    • single line: #or--
    • Multi-line:/*注释内容*/

DDL

database operation


  • Inquire
    • query all databasesshow DATABASES;
    • To query the current database, use the functionSELECT DATABASE();
  • Increase
    • Create a database CREATE DATABASE 数据库名, and an error will be reported when the database exists
    • If the database 不存在再创建:CREATE DATABASE IF NOT EXISTS 数据库名
    • When creating the database, specify 字符集 : CREATE DATABASE 数据库名 DEFAULT CHARSET utf8mb4, add the default character encoding after the database creation statement, the encoding is used utf8mb4, this encoding is included utf8, but it can also store 4 bytes of encoding, so that it can store the expression of the mobile terminal, etc.
  • delete
    • Delete database: DROP DATABASE 【IF EXISTS】 数据库名
      -Other :
    • Switch database: USE 数据库名: When operating data, be sure to switch to its database

Data table operation

  • Inquire
    • Query current 库所有表:SHOW TABLES;
    • view 表结构:DESC 表名
    • Query the table creation statement of the specified table:SHOW CREATE TABLE 表名
  • CREATE
    • create a tableCREATE TABLE 表名(字段1 类型 【comment 字段注释】,字段2 类型 【comment 字段注释】)【comment 表注释】
      表的数据类型
      • numeric
type Bytes signed range
tinyInt 1 Negative (2( 8-1) power divided by 2) ~ Positive ((2( 8-1) power divided by 2)-1)
smallInt 2 Negative (2( 16-1) power divided by 2) ~ Positive ((2( 16-1) power divided by 2)-1)
mediumInt 3 Negative (2( 24-1) power divided by 2) ~ Positive ((2( 24-1) power divided by 2)-1)
int 4 Negative (2( 32-1) power divided by 2) ~ Positive ((2( 32-1) power divided by 2)-1)
bigInt 8 Negative (2( 64-1) power divided by 2) ~ Positive ((2( 64-1) power divided by 2)-1)
float 4
double 8
decimal(M,D) M+2 bytes Fixed-point numbers manually specify precision and scale precision = decimal places + integer digits scale = decimal places十分精准,但占用空间

Numerical types should pay attention to the sign bit. In the integer type, there is a bit used as the sign bit. If the sign is not used, it means that the range is from (0, 2 to the power of the bit number - 1). The unsigned type of the floating point number is only signed
. 0 and positive digits, 实际范围并未扩大, just omit the decimal part

  • character type
type byte size describe
char 0~255 Fixed-length string, need to specify the length 指定多长,就占用多少字符空间but high efficiency
varchar 0~65535 Variable-length character string, need to specify the maximum length. 占用多少字符空间,与具体存储有关More flexible than Char, but less efficient
text 0~65535 Data suitable for long text
Ability to use fixed lengths charas it is more efficient
  • datetime
type Occupied bytes describe
Date 3 Date value YYYY-MM-DD
Time 3 time value HH:MM:ss
Year 1 Year value YYYY range 1901~2155
DateTime 8 Date and time values ​​YYYY-MM-DD HH:MM:SS range 1000-01-01 00:00:00 to 9999-12-31 23:59:59
TIMESTAMP 4 The date and time value YYYY-MM-DD HH:MM:SS 1970-01-01 00:00:01to 2038-01-19 03:14:07 is stored as a timestamp and will be automatically converted according to the current time zone

Alter table ALTER

  • Add fields ADD:ALTER TABLE 表名 ADD 字段名 类型 【注释】【约束】
  • Modify field type MODIFY:ALTER TABLE 表名 MODIFY 字段名 类型
  • Modify the field name and field type CHANGE:ALTER TABLE 表名 CHANGE 旧字段 新字段 类型 【注释】【约束】
  • Delete field DROP:ALTER TABLE 表名 DROP 字段名
  • Modify the table name RENAME:ALTER TABLE 表名 RENAME TO 新表名

Delete DROP
- 删除表: DROP TABLE 【IF EXISTS】表名
- Create a table after deleting, which is equivalent to performing a 截断:TRUNCATE TABLE 表名


insert image description here

DML

There is no big difference between adding data INSERT
VALUE and VALUES, they can be mixed

  • to 指定字段add dataINSERT INTO 表名(字段1,字段2,字段3) VALUES(字段1的值,字段2的值,字段3的值)
  • Add data to all fields
    • write all fieldsINSERT INTO 表名(字段1,字段2,字段3) VALUES(字段1的值,字段2的值,字段3的值)
    • Omit the field name and write the table name directlyINSERT INTO 表名 VALUES(字段1的值,字段2的值,字段3的值)
  • Adding data in batches does not change the front, and the backVALUES(第一组值),(第二组值),(第三组值)...

Note :

  1. The order of the values ​​in VALUES should be the same as the data table field (when no field is specified) or the specified字段顺序一一对应
  2. The string date function needs to add ''a sign
  3. The inserted data size must conform to the set data type range

delete data

  • Delete data: DELETE FROM 表名 【WHERE 条件】Deleting data can only delete one row, but cannot delete the data of a certain field. You can use the DDL statement to delete the entire field data ALTER TABLE 表名 DROP 字段名, and to delete a certain value of the field, you can useUPDATE语句将其置空

Modify data UPDATE

  • Modify data: UPDATE 表名 SET 字段1=值1,字段2=值2... FROM 表名 【WHERE 条件】; If the condition is not written, the data of the entire table will be modified; if the condition is specified, only the data of the symbol condition will be modified

DQL

single table query

query statement structure
SELECT 字段列表 FROM 表名 WHERE 条件 GROUP BY 分组条件 HAVING 分组后的条件 ORDER BY 根据哪些字段排序 LIMIT 分页参数

simple query

  • Querying multiple fields SELECT 字段1、字段2 FROM 表名 WHERE 条件is not recommended SELECT * FORM 表名..because *the query efficiency is low
  • Set the table name for the field
    • You can directly add an alias after a space after the field to be queriedSELECT 字段1 别名1
    • Add after the field to be queriedSELECT 字段1 AS 别名1
  • Remove duplicate records when queryingSELECT DISTINCT 字段列表 FROM 表名

Notice

  • _Represents matching characters, %representing matching 任意个characters
  • Empty or not empty to use IS NULLand IS NOT NULL to represent
  • BETWEEN x AND yRange includes xand y
    aggregate functions
    treat the entire field as a whole纵向计算
Function name effect
count() Count the number of longitudinal data in a field
max() Count this field (column)最大的值
min() Count this field (column)最小的值
avg() Count this field (column)平均值
sum() Count this field (column)总和

分组查询
where条件查询后的数据 跟据某一字段按照相同值进行分组,分组后的数据可以使用HAVING进行过滤
HAVINGWHERE的区别

  • 执行的先后顺序不一样,HAVING执行在分组后,分组又在WHRER查询后
  • HAING可以使用聚合函数进行再一次过滤

分组字段数据相同的有几组,结果就会显示几条数据

注意:
1、分组查询的字段应为聚合函数和用来分组的字段 ,否则无意义
要在每个分组中只能查询出一行数据,和聚合函数是对每组数据进行压缩成一个数据,每组字段每组也只有一个
例:统计男女生人数  :按照性别进行分组,最后只会有两行数据   在字段中使用聚合函数的COUNT(*)将每组数据进行统计个数
最后显示两行数据,一行是分组的男生数据,另一行是女生数据 。 字段只适合符合分组条件,例如字段加上一个姓名,男生组中出现一个姓名,女生组出现一个姓名 ,只有两行数据毫无意义
2、可以根据多个字段进行分组  GROUP BY 字段1 ,字段2 ,最后数据个数为 字段1*字段2
3、HAVING必须要跟在GROUP By之后

insert image description here

insert image description here
排序方式

  • ASC 升序 (默认)

  • DESC 降序

  • 按照某个字段1进行升序排序,顺序相同时,在按照字段2进行降序排序 ORDER BY 字段1 ASC,字段2 DESC

分页查询
SELECT 字段列表FROM 表名 LIMIT 起始索引,数据条数

注意 
1、若不指定起始索引,默认为0
2、起始索引=(页数-1)* 每页显示条数
3、LIMIT是MySQL的方言,不同的数据库分页有不同的实现方法

例如:查询第三页人员的姓名,每页显示5条数据
这里第三页起始页数,根据起始索引=(起始页数-1) * 每页的大小 ,每页的大小为5 即可获取起始索引,所以在查询语句后面添上LIMI 起始索引,每页大小

总结
insert image description here

执行顺序

先要知道从哪张表查,数据条件过滤,要查询哪些字段?将查询的出的数据按照什么顺序排列?要几个数据?

insert image description here

insert image description here


多表查询

利用表与表的关系,通过一条SQL语句查询多张表的数据

多表关系

一对一
表中一条数据对应另一张表的一条数据,
那么为什么不合为一张表呢?

  • 将单表进行拆分,既能提升查询效率 也方便管理。例如将用户表分为用户基础信息表和用户详情表,这样在可以根据需求进行不同粒度的查询,提升效率

怎样实现一对一的关系呢?

  • 一张表的字段关联着另一张表的主键,且子表的该字段唯一,这样就能确保一张表中只有一条数据与另一张表中的一条数据相对应
    使用外键是确定表中数据间的关系从而确保数据完整性,使用唯一约束是确保只有一条数据(唯一)对应另一条数据(主键唯一)

多对一、一对多
这种比较常见,比如图书一个管理员要保管多个图书,一个部门对应多个员工,如果把他们放在一张表,那么多的一方字段会大量的冗余。
怎样实现多对一的关系呢?
多对一和一对多是同一种关系,只是主体不同罢了。实现使用的一方外建于的一方的主键,并保存的一方的主键。
这样就能确保数据完整性的同时,也能通过多的一方找到一的一方。
例如,员工表保存部门的id。

  • 查询员工的部们信息时,通过其字段保存的部门主键去部门表中查找对应数据即可
  • 查询此部门对用所有的员工信息,也同样去员工表查询保存部们的字段=此部门id即可

多对多
一张表的多数据可能对应另一张的多条数据,没有的一方了,这时就需要一张表单独去保存他们的对应关系。例如课程学生,一个学生对应多个课程,一个课程也对应多个学生,这时就不需要这两张表建立关联,只需要再去创建一张学生课程关系表去记录哪一学生有哪一门课
例如:

insert image description here

连接查询

如果直接去查询两张表,那么将会形成笛卡尔积
insert image description here
两张表没有关系的数据内容也会在一条数据显示

insert image description here
那么怎样解决呢? 过滤!

在将这些数据按照条件就行过滤,条件就是这两张表的关系 。例如在语句后面添加上WHERE tbl_cla.id= tbl_stu.class_id,这样就成功查出了学生信息与其对应的班级信息
insert image description here
而这种两张表连接的方式也叫隐式内连接,此外还有多种不同的方式

连接分类

在表连接时建议给表起别名,但一但起别名就不能使用原表名。在指定两张表的连接条件时,不能使用字段的别名,要使用表名/表的别名.字段原名 ,因为根据SQL的执行顺序,在执行WHERE语句时还没有执行到SELECT,对于字段的别名来说是未知的

内连接 JOIN

内连接相当于求两张表的交集部分
insert image description here
例如:有员工表和部门表,那么通过内连接能够查询出每一个员工对应的部门,对于有部门没有员工和有员工没有部门的将会被舍去
隐式内连接
SELECT 字段列表 FROM 表1 ,表2 WHERE 连接条件

把两张表的数据全部查取出来,再通过字段共同部分进行过滤,从而查取出两张表中每条关联的数据。没有关联的数据将会被过滤掉,所以是两张表的交集
显式内连接
SELECT 字段 FROM 表1 (INNER)JOIN 表2 ON 连接条件
求两张表的交集部分的另一种写法

外连接
左外连接 LEFT JOIN

insert image description here
例如 ,同样是员工表和部门表,如果员工表左外连接部门表,则会查询所有员工以及对应的部门,当然这样就会包含没有部门的员工,会省略没有员工的部门

SELECT 字段 FROM 表1 LEFT(OUTER)JOIN 表2 ON 连接条件

右外连接 RIGHT JOIN

insert image description here
同左外连接,只是这次是去查询右表与左表的公共部分
例 :员工表和部门表,如果员工表右外连接查询部门表,则查询的数据是每个部门包含的员工信息,也包括没有员工的部门,省略没有部门的员工
SELECT 字段 FROM 表1 RIGHT (OUTER)JOIN 表2 ON 连接条件

左外连接和右外连接可以通过改变表的连接顺序实现转换,例如:上面的例子也可以通过部门表左外连接员工表实现,多数时使用的是左外连接

自连接 JOIN

同一张表再次连接自己,查询一张表中数据有关联的部分。例如,一张员工表,表中记录着员工的信息和领导的id,而领导也在这张表。一张表中数据和数据存在关联部分,通过自连接即可查询到每一个领导对应的员工的信息等

自连接一定要给表起别名,否则都是一张表怎样去区分是哪张表呢?

SELECT 字段 FROM 表1 别名 JOIN 表1 别名 ON 表中数据关系部分,自连接的语法同内连接,只是同一张表间的连接

联合查询 UNION

联合查询相当于把两次查询的数据进行纵向的拼接,条件是表的字段列数以及类型必须一一对应,否则纵向拼接怎样对齐数据呢?分为两种方式,一种是允许重复即允许一条数据多次显示 关键字UNION ALL;一种是拼接后进行去重 ,关键字UNION

同样是员工表,我想要查询员工年龄大于30 的,在查询工资大于1万的,将查询的数据进行纵向拼接,则可能会出现年龄既大于30工资又大于1万的重复显示,忽视则UNION ALL,去重则UNION
查询的语法就像条SQL通过一个关键字UNION/UNION ALL 进行连接

SELECT 字段 FORM 表 
UNION
SELECT 字段 FROM 表

为什么不使用一条语句呢?因为是要求的是查询字段类表即类型相同,而不是表的所有字段,这样就会出现不同的表,每张表满足不同的条件进行相同字段的连接

同样是员工表与部门表,要查询员工表人数大于20 的部门的id和位置在北京的部门id,两张不同表通过不同的条件查询出相同的字段进行拼接即可得出 位置在北京同时人数大于20的部门id

子查询

SQL语句中将另一条SQL的查询结果作为条件进行查询,SQL嵌套

标量子查询

返回的数据为单个值
常用的查询条件:= <> > >= < <=
例如:查询A班级的所有学生信息 。 学生表中存放的是班级的id字段,通过班级id作为条件,就要查询A班级对应的id,只能有一个数据所以是标量子查询

列子查询

查询一列数据,即一个字段的多条数据,通常是作为一个字段的条件范围
常用的查询条件:IN 、NOT IN 、 ANY 、SOME 、 ALL
例如:查询班级编号为A和B的所有学生信息。A和B会查询出两条id数据,只要在查询学生表时要求学生的班级id在这班级id范围内即可

行子查询

查询一行的可能多个字段的数据
常用的查询条件:= 、<> 、IN 、NOT IN
用于要查询的数据需要多个有关子查询的条件
例如 有两张表,要查询A部门的员工家庭住址和A部门所在地相同的员工信息
要先查询A部门对应的部门id,和A部门的地址。子查询是一行有多个字段的数据作为条件,这就是 行子查询

语句就为 SELECT * FROM emp WHERE (dep_id,addr)=(SELECT id,addr FROM dpt WHERE name='A')

表子查询

行子查询有多条数据或者说列子查询有多个字段,多条数据多个字段,子查询查询出的即是一张表
例如:查询所有 员工的家庭地址与其所在部门地址相同的员工信息
首先就要查询所以部门的id以及地址,多个字段多条数据相当于一张表 作为查询员工表的条件。
常用的查询条件in
语句就为 SELECT * FROM emp WHERE (dep_id,addr) in (SELECT id,addr FROM dpt)

DCL

数据库权限管理语句,对系统的管理不止可以使用语句,还可以使用命令行,由于对于开发,这里只做了解,只介绍部分使用语句的情况

认证管理
系统中所有的用户信息(用户名、密码等)也放在了一张表中,此表在系统数据库,库名为mysql,库表为user


查询

  • 查询此系统中的所有用户:查询所有用户即要查询user表中所有的数据 SELECT * FROM mysql.user

添加

  • 注册一个用户:注意注册用户并不是向表中添加一条数据,而是由专门的语句 CREATE USER '用户名'@'登录时指定的ip' IDENTIFIED BY '密码'

    • 值的注意的是
      • 主机ip使用来限制用户可以从哪台主机进行登录,可以使用通配符%,代表任意主机
      • 用户登录要满足三个条件,用户名正确,在指定的ip登录,密码正确
      • 用户创建完成后,没有任何权限,需要后面的赋值操作,否则登录后只会显示一张表 information_schema
        insert image description here

修改

  • 修改用户密码:ALTER USER '用户名'@'主机ip' IDENTIFIED WITH mysql_native_password BY '新密码'
    也可修改主机名、用户名,这里不再介绍

删除

  • 删除用户 DROP USER '用户名'@'主机名'

授权管理
除了root用户其他用户注册后必须还有为其授权权限,否则没有只能登录,登录后只能看到一张系统的表,上面已经介绍过。
权限是精确到表的

权限都有哪些常见的、可供授予的呢?

权限名称 描述
SELECT 查询权限
INSERT 插入权限
UPDATE 修改数据权限
DELETE 删除权限
CREATE 创建库表权限
ALTER 修改权限
DROP 删除表、库、视图权限
ALL, ALL PRIVILEGES 所有权限

查询谁哪些权限 SHOW GRANTS FOR '用户名'@‘主机名’
授权谁哪些权限 GRANT 权限1 , 权限2 .. ON 数据库名.表名 TO ‘用户名’@‘主机名’
撤销谁哪些权限REVOKE 权限1 , 权限2 .. ON 数据库名.表名 FROM ‘用户名’@‘主机名’

数据库和数据表可以使用通配符*代表所有,所有权限可以使用ALL, ALL PRIVILEGES
总结
insert image description here

函数

函数是SQL数据库管理系统中自己封装的一段SQL语句,可以直接调用其去执行相应的功能

这里列举一些常见函数

字符串函数

对字符串类型的数据进行处理,最后返回一个字符串

  • CONTANT(‘a1’,‘a2’,‘a3’):字符串拼接,放在参数列表中的各个参数将会按照先后顺序被拼接成一个字符串返回

    • 例:
      insert image description here
  • LOWER(‘xxx’) :全部转为小写 将参数中所有字母全部转为小写返回


    • insert image description here
  • UPPER(‘xxx’):全部转为大写,将函数参数列表中所有字母全部转为大写


    • insert image description here
  • LPAD(‘str’,n,‘xxx’):字符串左填充,参数列表分别是 要进行填充的字符串、一共要达到的个数、用什么填充 ,最后返回一个处理后的字符串

    • 例:
      insert image description here
  • RLAD(‘str’,n,‘xxx’):字符串右填充,与上面不同的是,当原字符串没有满足指定的个数时,将会从右边进行填充
    insert image description here

  • TRIM(‘str’):去除左右两边的空格,注意是不能去除中间空格的


    • insert image description here
    • SUBSTRING(‘str’,startNum,截取长度):指定从哪个位置截取几个字符,注意:是从1开始查到startNum,截取包含startNum位置的字符

      • insert image description here

数值型函数

  • CEIL(num):向上取整,小数一律进一法取整 CEIL翻译为:天花板


    • insert image description here
  • FLOOR(num):向下取整,只要整数部分 FLOOR翻译为:地板


    • insert image description here
  • MOD(x,y):取模运算 ,相当于将x/y,取模即取前者除以后者的余数


    • insert image description here
    • 表示除法不用去使用函数,直接使用运算法即可
      insert image description here
  • RAND():生成0~1之间的随机数 rand 翻译为:胡乱的,随机的


    • insert image description here
  • ROUND(num,y):将小数进行四舍五入,y指的是小数要保留的小数位数


    • insert image description here
      练习小案例:通过数据库的函数,生成一个六位数的随机验证码。
    随机数乘上1000000,会取得6位数的整数和一堆小数,采用ROUD()进行四舍五入或 CEIL()进一、或FLOOR()取整 等。总之要去掉小数
    考虑到可能会有 0.0xxxxxxxx 通过乘和去小数后变为 0xxxxx,0又会自动省略,造成最后不满足6位,所以要对生成的整数进行填充。
    使用LPAD()、RPAD()都可以。
    SELECT LPAD(ROUND(RAND()*1000000),6,'0')
    

日期函数

  • CURDATE():获取当前日期 CUR即current(翻译为 当前的)的简写,拼上DATE即日期


    • insert image description here
  • CURTIME() :获取当前时间 同理,CUR+TIME


    • insert image description here
  • NOW():当前的日期和时间 ,相当于 CURDTAE()+CURTIME()


    • insert image description here
  • YEAR(date)、MONTH(date)、DAY(date):根据日期获取年份、月份、天数


    • insert image description here

    • insert image description here

时间类型的计算函数

  • DATE_ADD(date,INTERVAL num 时间单位):计算指定间隔后的日期/时间 INTERVAL 是固定的 后面接上 值 和 单位
    • 计算日期 则第一个参数传递的是 DATE型, 时间单位有YEAR,MONTH,DAY ,返回的是DATE类型

      • insert image description here
  • 计算时间 则第一个参数传递的是 DATETIME型或TIME型, 单位还可以为 HOURMINUTESECOND

    • insert image description here
  • DATEDIFF(date1,date2):计算时间间隔,返回天数 是前面的日期-后面日期的天数

    • insert image description here
  • TIMEDIFF(time1,time2):同理,返回的是时分秒
    • 例:
      insert image description here

流程函数

  • IF(bool,v1,v2): 如果bool如果为true,则返回v1,false则返回v2。相当于一个三目运算

    • insert image description here
    • IFNULL(v1,v2):如果为v1不为空则返回v1,反之返回v2
      • 例:
        insert image description here
  • CASE 字段 WHEN ‘值1’ THEN ‘返回值1’ WHEN ‘值2’ THEN ‘返回值2’…ELSE ‘返回值3’ END 当这个字段的值等于某个值时,返回什么值,如果都前面的值都不符合,就返回一个ELSE中的值

    • insert image description here
  • CASE WHEN(bool)THEN ‘返回值1’ WHEN (bool) THEN ‘返回值2’ ELSE ‘返回值3’ END 满足哪个条件就返回哪个值,都不满足返回false
    与前者的不同之处是,前者是用一个字段去挨个与WHEN去比较,这个要比较的值在一个CASE中可以不是固定的,它的特点是可以比较灵活,字段也可以多个

总结
insert image description here

约束

约束用来限制某个字段中应该插入什么样的数据(作用单位是字段),确保表中数据的正确性(如检查约束非空约束唯一约束),完整性(如 外键约束默认约束),

约束类型

约束名称 描述
主键约束 primary key 每一行数据的标识 非空且唯一
唯一约束 unique 在一张表中该字段所有数据不能重复
非空约束 not null 该字段不能为null (可以为空格)
默认约束 default 如果不指定值,则自定填土设定好的默认值
检查约束 check 该功能在sql8.0.16版本后才有 该字段的数据要满足的一定的条件
外键约束 foreign key 建立表与表之间的联系 ,字表的某个字段的数据要在父表某个字段数据的范围内

主键添加时机

  • 可以在创建表时,在字段类型后面指定约束 。例如创建一张表,将id设定为主键,将姓名设置为唯一
create TABLE tbl_user (id int primary key comment '编号',name varchar(20) unique comment '姓名')
  • 创建表时在末尾补上
create Table tbl_user (id int comment '编号',name varchar(20) unique comment '姓名' ,primary key(id))
  • 在创建表后,进行修改表添加字段约束 。
alter table tbl_user add primary key

主键删除时 alter table tbl_user drop primary

外键

外键使得两张表之间数据完整性。例如有一个班级表,有一个学生表,学生表中有一个字段时学生的班级,其字段值的范围肯定要在班级编号的范围内。所以建立外键约束,在插入时要检查学生表的班级id字段是否在班级id字段范围内。其中班级表就为父表,学生表就为字表
外键添加时机

  • 在创建表的末尾 指明此表的哪个字段要外键与哪张表的哪个字段
create table tbl_stu (id int PRIMARY KEY auto_increment ,class_id int ,FOREIGN KEY(id) REFERENCES tbl_class(id))
  • 修改表 时添加外键
ALTER TABLE tbl_stu Add constraint 外键名称 FOREIGN KEY(id) REFERENCES 主表 (外键的字段)

外键的删除

ALTER TABLE 表名 DROP FOREIGN KEY 外键名称 

删除表外键的时候要指定外键的名称,而在创建外键时如果不指定外键名称,系统会自动生成,但生成的不知道是啥,那怎么删除呢?(不使用客户端工具情况下)
使用一个命令那就查看建表语句,在语句中会显示外键的名称show create table 表名

Using the example at the beginning, since the class field of the student table has been foreign-keyed to the id field of the class table, what happens to the class field of the student table if the class table is deleted? If the parent table is deleted and the child table remains unchanged, the corresponding information for this field of the child table will not be found, resulting in incomplete data.
So how to solve it?
Effect of parent table delete/update behavior on child table

Strategy describe
NO ACTION RESTRICT mySQL default When modifying/deleting the parent table, if this piece of data has been constrained by other child tables as foreign keys, the data of the parent table is not allowed to be deleted (solution: delete the corresponding child table data)
CASCADE After the parent table is deleted, the corresponding child table data will also be deleted. Unlike the above method, the above method can only delete the child table first, and then the parent table can be deleted. And this is that the parent table will be deleted first, and then the data corresponding to the child table will be deleted
SET NULL After deleting the parent table, the corresponding entire piece of data in the child table will not be deleted, but the value of the corresponding field will be blank
SET DEFAULT Innodb不支持 The difference from the above is that it will not be left blank, but can be specified as a default value, but the database engineInnodb不支持

Which one to choose can be specified when configuring the foreign key. When specifying, it is divided into modification and deletion. If not specified, the default is. NO ACTION
For example:ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段)REFERENCES 主表名(字段) ON UPDATE xxx ON DELETE xxx

Guess you like

Origin blog.csdn.net/m0_52889702/article/details/128213863