文章目录
- [3 SQL 语言](#3 SQL 语言)
-
- 3.1关系型数据库的构成
- [3.2 SQL语言介绍](#3.2 SQL语言介绍)
-
- [3.2.1 SQL 语言规范](#3.2.1 SQL 语言规范)
- 3.2.2数据库对象和命名
- [3.2.3 SQL 语句分类](#3.2.3 SQL 语句分类)
- [3.2.4 SQL 语句构成](#3.2.4 SQL 语句构成)
- 3.2.5字符集和排序
- 3.3管理数据库
-
- 3.3.1查看数据库列表
- [3.3.2 创建数据库](#3.3.2 创建数据库)
- [3.3.3 修改数据库](#3.3.3 修改数据库)
- 3.3.4删除数据库
- 3.4数据类型
- [3.5 DDL 语句](#3.5 DDL 语句)
- [3.6 DML 语句](#3.6 DML 语句)
-
- 3.6.1插入数据
- [3.6.2 更新数据](#3.6.2 更新数据)
- [3.6.3 删除数据](#3.6.3 删除数据)
- [3.7 DQL 语句](#3.7 DQL 语句)
- [3.8 MySQL用户管理](#3.8 MySQL用户管理)
- 3.9权限管理和DCL语句
-
- [3.9.1 权限类别](#3.9.1 权限类别)
- [3.9.2 授权](#3.9.2 授权)
- [3.9.3 取消权限](#3.9.3 取消权限)
- 3.9.4查看用户权限
- 3.10MySQL图形化远程管理工具
-
- [3.10.1 Navicat 工具](#3.10.1 Navicat 工具)
- [3.10.2 SQLyog 工具](#3.10.2 SQLyog 工具)
- 3.11实现基于LAMP架构的开源网站
-
- [3.11.1 LAMP 架构说明](#3.11.1 LAMP 架构说明)
- [3.11.2 PHP 简介](#3.11.2 PHP 简介)
- 3.11.3实现博客项目
3 SQL 语言
3.1关系型数据库的构成
| 组件 | 关键字 | 说明 |
|---|---|---|
| 数据库 | database | 表的集合,一个数据库中可以有多个表,在文件系统中表出就是一个目录 |
| 表 | table | 在数据库中以二维表的形式出现,有行和列,数据库中的数据就是存放于表中的 |
| 索引 | index | 索引通常建立在一个列上,用以加快数据查询速度 |
| 视图 | view | 用SQL语言构建的虚拟表,可以临时把两个或多个表以逻辑关系关联上,对外提供查询 |
| 存储过程 | procedure | 存储过程是一组为了完成特定功能的SQL语句集合,客户端可以直接调用 |
| 存储函数 | function | 存储函数和存储过程一样,都是SQL语句集合,但可以使用参数 |
| 触发器 | tigger | 触发器也是有SQL语句的集合组成,但需要达到触发条件才能调用 |
| 事件调度器 | event scheduler | 数据库中的计划任务 |
| 用户 | user | 连接服务端时的用户名 |
| 权限 | privilege | 每个用户可以对哪些数据库或表进行操作,在什么IP能连接 |
3.2 SQL语言介绍
SQL:(Structured Query Language)结构化查询语言。
- SQL语言是对IBM公司San Jose,California研究实验室的埃德加·科德的关系模型的第一个商业化语言实现。尽管SQL并非完全按照科德的关系模型设计,但其依然成为最为广泛运用的数据库语言
- 1970年代初,由埃德加·科德发表将资料组成表格的应用原则(Codd's Relational Algebra)。
- 1974年,同一实验室的D.D.Chamberlin 和 R.F.Boyce对Codd's Relational Algebra在研制关系数据库管理系统System R中,研制出一套规范语言SEQUEL(Structured English Query Language)。
- 1976年11月的IBM Journal of R&D上公布新版本的 SQL(叫SEQUEL/2)。1980年改名为SQL。
- 1979年ORACLE公司首先提供商用的SQL,IBM公司在DB2和SQL/DS数据库系统中也实现了SQL。
- 1986年10月美国国家标准学会ANSI采用SQL作为关系数据库管理系统的标准语言(ANSIX3.135-1986)。
- 1987年成为国际标准化组织((ISO)采纳为国际标准。
- 1989年美国ANSI采纳在ANSIX3.135-1989报告中定义的关系数据库管理系统的SQL标准语言,称为 ANSI SQL 89。
- 后续SQL标准经过了一系列的增订,加入了大量新特性,有各种版本:ANSISQL,SQL-1986,SQL-1989,SQL-1992,SQL-1999,SQL-2003,SQL-2008,SQL-2011。
- 目前,所有主要的关系数据库管理系统支持某些形式的SQL,大部分数据库至少遵守ANSISQL89标准。
- 虽然有这一标准的存在,但大部分的SQL代码在不同的数据库系统中并不具有完全的跨平台性。
- 业内标准微软和 Sybase 的T-SQL,Oracle 的 PL/SQL。
3.2.1 SQL 语言规范
- 在数据库系统中,SQL语句不区分大小写,建议用大写。
- SQL语句可单行或多行书写,默认以 **;**结尾。
- 关键词不能跨多行或简写。
- 用空格和TAB缩进来提高语句的可读性。
- 子句通常位于独立行,便于编辑,提高可读性。
bash
#不区分大小写
mysql> select @@hostname;
+-----------------------+
| @@hostname |
+-----------------------+
| localhost.localdomain |
+-----------------------+
1 row in set (0.00 sec)
mysql> SELect @@HOSTname;
+-----------------------+
| @@HOSTname |
+-----------------------+
| localhost.localdomain |
+-----------------------+
1 row in set (0.00 sec)
#区分大小写
mysql> SELect user,host from mysql.user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
4 rows in set (0.01 sec)
mysql> SELect user,host from mysql.USER;
ERROR 1146 (42S02): Table 'mysql.USER' doesn't exist
mysql> SELect user,HOST from mysql.USER;
ERROR 1146 (42S02): Table 'mysql.USER' doesn't exist
#字段不区分大小写,库名表名区分大小写
mysql> SELect user,HOST from mysql.user;
+------------------+-----------+
| user | HOST |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
范例:跨行
bash
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.01 sec)
mysql> show
-> databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
#关键字不能跨行
mysql> show data
-> bases;
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 'data
bases' at line 1
SQL语言中的注释
SQL语言中的标准注释
mysql
-- select version()\G #单行注释
/* #多行注释
select version()\G
select version()\G
*/
select version()\G
范例:
bash
[root@localhost ~]# vim test.sql
-- select version()\G
/*
select version()\G
select version()\G
*/
select version()\G
[root@localhost ~]# mysql < test.sql
*************************** 1. row ***************************
version(): 8.0.26
MySQL中的注释
bash
# select version()\G; #MySQL中的注释
select version()\G;
范例:
bash
[root@localhost ~]# cat test.sql
# select version()\G;
# select version()\G;
select version()\G;
[root@localhost ~]# mysql < test.sql
*************************** 1. row ***************************
version(): 8.0.26
3.2.2数据库对象和命名
数据库中的组件(对象)
bash
数据库、表、索引、视图、用户、存储过程、函数、触发器、事件调度器等
组件命名规则
- 可以包括字母,数字和三个特殊字符(#_$)
- 不能使用MySQL的保留字
3.2.3 SQL 语句分类
| SQL语句类型 | 说明 | 具体语句 |
|---|---|---|
| DDL | Data Defination Language数据定义语言 | CREATE,DROP,ALTER |
| DML | Data Mainpulation Language数据操纵语言 | INSERT,DELETE,UPDATE |
| DQL | Data Query Language数据查询语言 | SELECT |
| DCL | Data Control Language数据控制语言 | GRANT,REVOKE |
| TCL | Transaction Control Language事务控制语言 | BEGIN,COMMIT,ROLLBACK,SAVEPOINT |
3.2.4 SQL 语句构成
关键字keyword组成子句clause,多条clause组成语句
mysql
mysql> SELECT host,user,authentication_string FROM mysql.user WHERE authentication_string = '';
+-----------+------+-----------------------+
| host | user | authentication_string |
+-----------+------+-----------------------+
| localhost | root | |
+-----------+------+-----------------------+
1 row in set (0.00 sec)
说明:
bash
SELECT host,user,authentication_string #select子句
FROM mysql.user #from子句
WHERE authentication_string = ''; #where子句
命令行下查看帮助
mysql
mysql> help contents;
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
Account Management
Administration
Components
Compound Statements
Contents
Data Definition
Data Manipulation
Data Types
Functions
Geographic Features
Help Metadata
Language Structure
Loadable Functions
Plugins
Prepared Statements
Replication Statements
Storage Engines
Table Maintenance
Transactions
Utility
mysql> help Data Definition #查看DDL帮助
You asked for help about help category: "Data Definition"
For more information, type 'help <item>', where <item> is one of the following
topics:
ALTER DATABASE
ALTER EVENT
ALTER FUNCTION
ALTER INSTANCE
ALTER LOGFILE GROUP
ALTER PROCEDURE
ALTER SCHEMA
ALTER SERVER
ALTER TABLE
ALTER TABLESPACE
ALTER VIEW
CREATE DATABASE
CREATE EVENT
CREATE FUNCTION
CREATE INDEX
CREATE LOGFILE GROUP
CREATE PROCEDURE
CREATE SCHEMA
CREATE SERVER
CREATE SPATIAL REFERENCE SYSTEM
CREATE TABLE
CREATE TABLESPACE
CREATE TRIGGER
CREATE VIEW
DROP DATABASE
DROP EVENT
DROP FUNCTION
DROP INDEX
DROP PROCEDURE
DROP SCHEMA
DROP SERVER
DROP SPATIAL REFERENCE SYSTEM
DROP TABLE
DROP TABLESPACE
DROP TRIGGER
DROP VIEW
FOREIGN KEY
RENAME TABLE
TRUNCATE TABLE
mysql> help CREATE DATABASE;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_option] ...
create_option: [DEFAULT] {
CHARACTER SET [=] charset_name
| COLLATE [=] collation_name
| ENCRYPTION [=] {'Y' | 'N'}
}
CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.
URL: https://dev.mysql.com/doc/refman/8.0/en/create-database.html
3.2.5字符集和排序
早期MySQL版本默认为latin1,从MySQL8.0开始默认字符集已经为utf8mb4
查看当前版本可用的字符集
mysql
mysql> show CHARACTER SET; #查看所有支持的字符集
+----------+---------------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+---------------------------------+---------------------+--------+
| armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| binary | Binary pseudo charset | binary | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
| euckr | EUC-KR Korean | euckr_korean_ci | 2 |
| gb18030 | China National Standard GB18030 | gb18030_chinese_ci | 4 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| greek | ISO 8859-7 Greek | greek_general_ci | 1 |
| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |
| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |
| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
| utf16 | UTF-16 Unicode | utf16_general_ci | 4 |
| utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |
| utf32 | UTF-32 Unicode | utf32_general_ci | 4 |
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
| utf8mb4 | UTF-8 Unicode | utf8mb4_0900_ai_ci | 4 |
+----------+---------------------------------+---------------------+--------+
41 rows in set (0.00 sec)
mysql> show CHARSET; #查看所有支持的字符集
查看当前默认字符集
bash
mysql> show variables like 'character%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8mb3 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.01 sec)
修改mariadb-server的默认字符集
bash
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysql/mysqld.log
pid-file=/run/mysqld/mysqld.pid
character-set-server=latin1 #新加一行
[root@localhost ~]# vim /etc/my.cnf.d/client.cnf
[client]
default-character-set=latin1 #新加一样
[root@localhost ~]# systemctl restart mysqld #重启服务
mysql> show variables like 'character%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8mb3 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
#再改回来,或者还原快照
查看当前版本可用的排序规则
bash
mysql> SHOW COLLATION;
+----------------------------+----------+-----+---------+----------+---------+---------------+
| Collation | Charset | Id | Default | Compiled | Sortlen | Pad_attribute |
+----------------------------+----------+-----+---------+----------+---------+---------------+
| armscii8_bin | armscii8 | 64 | | Yes | 1 | PAD SPACE |
| armscii8_general_ci | armscii8 | 32 | Yes | Yes | 1 | PAD SPACE |
| ascii_bin | ascii | 65 | | Yes | 1 | PAD SPACE |
| ascii_general_ci | ascii | 11 | Yes | Yes | 1 | PAD SPACE |
| big5_bin | big5 | 84 | | Yes | 1 | PAD SPACE |
| big5_chinese_ci | big5 | 1 | Yes | Yes | 1 | PAD SPACE |
| binary | binary | 63 | Yes | Yes | 1 | NO PAD |
| cp1250_bin | cp1250 | 66 | | Yes | 1 | PAD SPACE |
| cp1250_croatian_ci | cp1250 | 44 | | Yes | 1 | PAD SPACE |
| cp1250_czech_cs | cp1250 | 34 | | Yes | 2 | PAD SPACE |
| cp1250_general_ci | cp1250 | 26 | Yes | Yes | 1 | PAD SPACE |
| cp1250_polish_ci | cp1250 | 99 | | Yes | 1 | PAD SPACE |
| cp1251_bin | cp1251 | 50 | | Yes | 1 | PAD SPACE |
| cp1251_bulgarian_ci | cp1251 | 14 | | Yes | 1 | PAD SPACE |
| cp1251_general_ci | cp1251 | 51 | Yes | Yes | 1 | PAD SPACE |
| cp1251_general_cs | cp1251 | 52 | | Yes | 1 | PAD SPACE |
| cp1251_ukrainian_ci | cp1251 | 23 | | Yes | 1 | PAD SPACE |
| cp1256_bin | cp1256 | 67 | | Yes | 1 | PAD SPACE |
| cp1256_general_ci | cp1256 | 57 | Yes | Yes | 1 | PAD SPACE |
| cp1257_bin | cp1257 | 58 | | Yes | 1 | PAD SPACE |
| cp1257_general_ci | cp1257 | 59 | Yes | Yes | 1 | PAD SPACE |
| cp1257_lithuanian_ci | cp1257 | 29 | | Yes | 1 | PAD SPACE |
| cp850_bin | cp850 | 80 | | Yes | 1 | PAD SPACE |
| cp850_general_ci | cp850 | 4 | Yes | Yes | 1 | PAD SPACE |
| cp852_bin | cp852 | 81 | | Yes | 1 | PAD SPACE |
| cp852_general_ci | cp852 | 40 | Yes | Yes | 1 | PAD SPACE |
| cp866_bin | cp866 | 68 | | Yes | 1 | PAD SPACE |
| cp866_general_ci | cp866 | 36 | Yes | Yes | 1 | PAD SPACE |
| cp932_bin | cp932 | 96 | | Yes | 1 | PAD SPACE |
| cp932_japanese_ci | cp932 | 95 | Yes | Yes | 1 | PAD SPACE |
| dec8_bin | dec8 | 69 | | Yes | 1 | PAD SPACE |
| dec8_swedish_ci | dec8 | 3 | Yes | Yes | 1 | PAD SPACE |
| eucjpms_bin | eucjpms | 98 | | Yes | 1 | PAD SPACE |
| eucjpms_japanese_ci | eucjpms | 97 | Yes | Yes | 1 | PAD SPACE |
| euckr_bin | euckr | 85 | | Yes | 1 | PAD SPACE |
| euckr_korean_ci | euckr | 19 | Yes | Yes | 1 | PAD SPACE |
| gb18030_bin | gb18030 | 249 | | Yes | 1 | PAD SPACE |
| gb18030_chinese_ci | gb18030 | 248 | Yes | Yes | 2 | PAD SPACE |
| gb18030_unicode_520_ci | gb18030 | 250 | | Yes | 8 | PAD SPACE |
| gb2312_bin | gb2312 | 86 | | Yes | 1 | PAD SPACE |
| gb2312_chinese_ci | gb2312 | 24 | Yes | Yes | 1 | PAD SPACE |
| gbk_bin | gbk | 87 | | Yes | 1 | PAD SPACE |
| gbk_chinese_ci | gbk | 28 | Yes | Yes | 1 | PAD SPACE |
| geostd8_bin | geostd8 | 93 | | Yes | 1 | PAD SPACE |
| geostd8_general_ci | geostd8 | 92 | Yes | Yes | 1 | PAD SPACE |
| greek_bin | greek | 70 | | Yes | 1 | PAD SPACE |
| greek_general_ci | greek | 25 | Yes | Yes | 1 | PAD SPACE |
| hebrew_bin | hebrew | 71 | | Yes | 1 | PAD SPACE |
| hebrew_general_ci | hebrew | 16 | Yes | Yes | 1 | PAD SPACE |
| hp8_bin | hp8 | 72 | | Yes | 1 | PAD SPACE |
| hp8_english_ci | hp8 | 6 | Yes | Yes | 1 | PAD SPACE |
| keybcs2_bin | keybcs2 | 73 | | Yes | 1 | PAD SPACE |
| keybcs2_general_ci | keybcs2 | 37 | Yes | Yes | 1 | PAD SPACE |
| koi8r_bin | koi8r | 74 | | Yes | 1 | PAD SPACE |
| koi8r_general_ci | koi8r | 7 | Yes | Yes | 1 | PAD SPACE |
| koi8u_bin | koi8u | 75 | | Yes | 1 | PAD SPACE |
| koi8u_general_ci | koi8u | 22 | Yes | Yes | 1 | PAD SPACE |
| latin1_bin | latin1 | 47 | | Yes | 1 | PAD SPACE |
| latin1_danish_ci | latin1 | 15 | | Yes | 1 | PAD SPACE |
| latin1_general_ci | latin1 | 48 | | Yes | 1 | PAD SPACE |
| latin1_general_cs | latin1 | 49 | | Yes | 1 | PAD SPACE |
| latin1_german1_ci | latin1 | 5 | | Yes | 1 | PAD SPACE |
| latin1_german2_ci | latin1 | 31 | | Yes | 2 | PAD SPACE |
| latin1_spanish_ci | latin1 | 94 | | Yes | 1 | PAD SPACE |
| latin1_swedish_ci | latin1 | 8 | Yes | Yes | 1 | PAD SPACE |
| latin2_bin | latin2 | 77 | | Yes | 1 | PAD SPACE |
| latin2_croatian_ci | latin2 | 27 | | Yes | 1 | PAD SPACE |
| latin2_czech_cs | latin2 | 2 | | Yes | 4 | PAD SPACE |
| latin2_general_ci | latin2 | 9 | Yes | Yes | 1 | PAD SPACE |
| latin2_hungarian_ci | latin2 | 21 | | Yes | 1 | PAD SPACE |
| latin5_bin | latin5 | 78 | | Yes | 1 | PAD SPACE |
| latin5_turkish_ci | latin5 | 30 | Yes | Yes | 1 | PAD SPACE |
| latin7_bin | latin7 | 79 | | Yes | 1 | PAD SPACE |
| latin7_estonian_cs | latin7 | 20 | | Yes | 1 | PAD SPACE |
| latin7_general_ci | latin7 | 41 | Yes | Yes | 1 | PAD SPACE |
| latin7_general_cs | latin7 | 42 | | Yes | 1 | PAD SPACE |
| macce_bin | macce | 43 | | Yes | 1 | PAD SPACE |
| macce_general_ci | macce | 38 | Yes | Yes | 1 | PAD SPACE |
| macroman_bin | macroman | 53 | | Yes | 1 | PAD SPACE |
| macroman_general_ci | macroman | 39 | Yes | Yes | 1 | PAD SPACE |
| sjis_bin | sjis | 88 | | Yes | 1 | PAD SPACE |
| sjis_japanese_ci | sjis | 13 | Yes | Yes | 1 | PAD SPACE |
| swe7_bin | swe7 | 82 | | Yes | 1 | PAD SPACE |
| swe7_swedish_ci | swe7 | 10 | Yes | Yes | 1 | PAD SPACE |
| tis620_bin | tis620 | 89 | | Yes | 1 | PAD SPACE |
| tis620_thai_ci | tis620 | 18 | Yes | Yes | 4 | PAD SPACE |
| ucs2_bin | ucs2 | 90 | | Yes | 1 | PAD SPACE |
| ucs2_croatian_ci | ucs2 | 149 | | Yes | 8 | PAD SPACE |
| ucs2_czech_ci | ucs2 | 138 | | Yes | 8 | PAD SPACE |
| ucs2_danish_ci | ucs2 | 139 | | Yes | 8 | PAD SPACE |
| ucs2_esperanto_ci | ucs2 | 145 | | Yes | 8 | PAD SPACE |
| ucs2_estonian_ci | ucs2 | 134 | | Yes | 8 | PAD SPACE |
| ucs2_general_ci | ucs2 | 35 | Yes | Yes | 1 | PAD SPACE |
| ucs2_general_mysql500_ci | ucs2 | 159 | | Yes | 1 | PAD SPACE |
| ucs2_german2_ci | ucs2 | 148 | | Yes | 8 | PAD SPACE |
| ucs2_hungarian_ci | ucs2 | 146 | | Yes | 8 | PAD SPACE |
| ucs2_icelandic_ci | ucs2 | 129 | | Yes | 8 | PAD SPACE |
| ucs2_latvian_ci | ucs2 | 130 | | Yes | 8 | PAD SPACE |
| ucs2_lithuanian_ci | ucs2 | 140 | | Yes | 8 | PAD SPACE |
| ucs2_persian_ci | ucs2 | 144 | | Yes | 8 | PAD SPACE |
| ucs2_polish_ci | ucs2 | 133 | | Yes | 8 | PAD SPACE |
| ucs2_romanian_ci | ucs2 | 131 | | Yes | 8 | PAD SPACE |
| ucs2_roman_ci | ucs2 | 143 | | Yes | 8 | PAD SPACE |
| ucs2_sinhala_ci | ucs2 | 147 | | Yes | 8 | PAD SPACE |
| ucs2_slovak_ci | ucs2 | 141 | | Yes | 8 | PAD SPACE |
| ucs2_slovenian_ci | ucs2 | 132 | | Yes | 8 | PAD SPACE |
| ucs2_spanish2_ci | ucs2 | 142 | | Yes | 8 | PAD SPACE |
| ucs2_spanish_ci | ucs2 | 135 | | Yes | 8 | PAD SPACE |
| ucs2_swedish_ci | ucs2 | 136 | | Yes | 8 | PAD SPACE |
| ucs2_turkish_ci | ucs2 | 137 | | Yes | 8 | PAD SPACE |
| ucs2_unicode_520_ci | ucs2 | 150 | | Yes | 8 | PAD SPACE |
| ucs2_unicode_ci | ucs2 | 128 | | Yes | 8 | PAD SPACE |
| ucs2_vietnamese_ci | ucs2 | 151 | | Yes | 8 | PAD SPACE |
| ujis_bin | ujis | 91 | | Yes | 1 | PAD SPACE |
| ujis_japanese_ci | ujis | 12 | Yes | Yes | 1 | PAD SPACE |
| utf16le_bin | utf16le | 62 | | Yes | 1 | PAD SPACE |
| utf16le_general_ci | utf16le | 56 | Yes | Yes | 1 | PAD SPACE |
| utf16_bin | utf16 | 55 | | Yes | 1 | PAD SPACE |
| utf16_croatian_ci | utf16 | 122 | | Yes | 8 | PAD SPACE |
| utf16_czech_ci | utf16 | 111 | | Yes | 8 | PAD SPACE |
| utf16_danish_ci | utf16 | 112 | | Yes | 8 | PAD SPACE |
| utf16_esperanto_ci | utf16 | 118 | | Yes | 8 | PAD SPACE |
| utf16_estonian_ci | utf16 | 107 | | Yes | 8 | PAD SPACE |
| utf16_general_ci | utf16 | 54 | Yes | Yes | 1 | PAD SPACE |
| utf16_german2_ci | utf16 | 121 | | Yes | 8 | PAD SPACE |
| utf16_hungarian_ci | utf16 | 119 | | Yes | 8 | PAD SPACE |
| utf16_icelandic_ci | utf16 | 102 | | Yes | 8 | PAD SPACE |
| utf16_latvian_ci | utf16 | 103 | | Yes | 8 | PAD SPACE |
| utf16_lithuanian_ci | utf16 | 113 | | Yes | 8 | PAD SPACE |
| utf16_persian_ci | utf16 | 117 | | Yes | 8 | PAD SPACE |
| utf16_polish_ci | utf16 | 106 | | Yes | 8 | PAD SPACE |
| utf16_romanian_ci | utf16 | 104 | | Yes | 8 | PAD SPACE |
| utf16_roman_ci | utf16 | 116 | | Yes | 8 | PAD SPACE |
| utf16_sinhala_ci | utf16 | 120 | | Yes | 8 | PAD SPACE |
| utf16_slovak_ci | utf16 | 114 | | Yes | 8 | PAD SPACE |
| utf16_slovenian_ci | utf16 | 105 | | Yes | 8 | PAD SPACE |
| utf16_spanish2_ci | utf16 | 115 | | Yes | 8 | PAD SPACE |
| utf16_spanish_ci | utf16 | 108 | | Yes | 8 | PAD SPACE |
| utf16_swedish_ci | utf16 | 109 | | Yes | 8 | PAD SPACE |
| utf16_turkish_ci | utf16 | 110 | | Yes | 8 | PAD SPACE |
| utf16_unicode_520_ci | utf16 | 123 | | Yes | 8 | PAD SPACE |
| utf16_unicode_ci | utf16 | 101 | | Yes | 8 | PAD SPACE |
| utf16_vietnamese_ci | utf16 | 124 | | Yes | 8 | PAD SPACE |
| utf32_bin | utf32 | 61 | | Yes | 1 | PAD SPACE |
| utf32_croatian_ci | utf32 | 181 | | Yes | 8 | PAD SPACE |
| utf32_czech_ci | utf32 | 170 | | Yes | 8 | PAD SPACE |
| utf32_danish_ci | utf32 | 171 | | Yes | 8 | PAD SPACE |
| utf32_esperanto_ci | utf32 | 177 | | Yes | 8 | PAD SPACE |
| utf32_estonian_ci | utf32 | 166 | | Yes | 8 | PAD SPACE |
| utf32_general_ci | utf32 | 60 | Yes | Yes | 1 | PAD SPACE |
| utf32_german2_ci | utf32 | 180 | | Yes | 8 | PAD SPACE |
| utf32_hungarian_ci | utf32 | 178 | | Yes | 8 | PAD SPACE |
| utf32_icelandic_ci | utf32 | 161 | | Yes | 8 | PAD SPACE |
| utf32_latvian_ci | utf32 | 162 | | Yes | 8 | PAD SPACE |
| utf32_lithuanian_ci | utf32 | 172 | | Yes | 8 | PAD SPACE |
| utf32_persian_ci | utf32 | 176 | | Yes | 8 | PAD SPACE |
| utf32_polish_ci | utf32 | 165 | | Yes | 8 | PAD SPACE |
| utf32_romanian_ci | utf32 | 163 | | Yes | 8 | PAD SPACE |
| utf32_roman_ci | utf32 | 175 | | Yes | 8 | PAD SPACE |
| utf32_sinhala_ci | utf32 | 179 | | Yes | 8 | PAD SPACE |
| utf32_slovak_ci | utf32 | 173 | | Yes | 8 | PAD SPACE |
| utf32_slovenian_ci | utf32 | 164 | | Yes | 8 | PAD SPACE |
| utf32_spanish2_ci | utf32 | 174 | | Yes | 8 | PAD SPACE |
| utf32_spanish_ci | utf32 | 167 | | Yes | 8 | PAD SPACE |
| utf32_swedish_ci | utf32 | 168 | | Yes | 8 | PAD SPACE |
| utf32_turkish_ci | utf32 | 169 | | Yes | 8 | PAD SPACE |
| utf32_unicode_520_ci | utf32 | 182 | | Yes | 8 | PAD SPACE |
| utf32_unicode_ci | utf32 | 160 | | Yes | 8 | PAD SPACE |
| utf32_vietnamese_ci | utf32 | 183 | | Yes | 8 | PAD SPACE |
| utf8mb4_0900_ai_ci | utf8mb4 | 255 | Yes | Yes | 0 | NO PAD |
| utf8mb4_0900_as_ci | utf8mb4 | 305 | | Yes | 0 | NO PAD |
| utf8mb4_0900_as_cs | utf8mb4 | 278 | | Yes | 0 | NO PAD |
| utf8mb4_0900_bin | utf8mb4 | 309 | | Yes | 1 | NO PAD |
| utf8mb4_bin | utf8mb4 | 46 | | Yes | 1 | PAD SPACE |
| utf8mb4_croatian_ci | utf8mb4 | 245 | | Yes | 8 | PAD SPACE |
| utf8mb4_cs_0900_ai_ci | utf8mb4 | 266 | | Yes | 0 | NO PAD |
| utf8mb4_cs_0900_as_cs | utf8mb4 | 289 | | Yes | 0 | NO PAD |
| utf8mb4_czech_ci | utf8mb4 | 234 | | Yes | 8 | PAD SPACE |
| utf8mb4_danish_ci | utf8mb4 | 235 | | Yes | 8 | PAD SPACE |
| utf8mb4_da_0900_ai_ci | utf8mb4 | 267 | | Yes | 0 | NO PAD |
| utf8mb4_da_0900_as_cs | utf8mb4 | 290 | | Yes | 0 | NO PAD |
| utf8mb4_de_pb_0900_ai_ci | utf8mb4 | 256 | | Yes | 0 | NO PAD |
| utf8mb4_de_pb_0900_as_cs | utf8mb4 | 279 | | Yes | 0 | NO PAD |
| utf8mb4_eo_0900_ai_ci | utf8mb4 | 273 | | Yes | 0 | NO PAD |
| utf8mb4_eo_0900_as_cs | utf8mb4 | 296 | | Yes | 0 | NO PAD |
| utf8mb4_esperanto_ci | utf8mb4 | 241 | | Yes | 8 | PAD SPACE |
| utf8mb4_estonian_ci | utf8mb4 | 230 | | Yes | 8 | PAD SPACE |
| utf8mb4_es_0900_ai_ci | utf8mb4 | 263 | | Yes | 0 | NO PAD |
| utf8mb4_es_0900_as_cs | utf8mb4 | 286 | | Yes | 0 | NO PAD |
| utf8mb4_es_trad_0900_ai_ci | utf8mb4 | 270 | | Yes | 0 | NO PAD |
| utf8mb4_es_trad_0900_as_cs | utf8mb4 | 293 | | Yes | 0 | NO PAD |
| utf8mb4_et_0900_ai_ci | utf8mb4 | 262 | | Yes | 0 | NO PAD |
| utf8mb4_et_0900_as_cs | utf8mb4 | 285 | | Yes | 0 | NO PAD |
| utf8mb4_general_ci | utf8mb4 | 45 | | Yes | 1 | PAD SPACE |
| utf8mb4_german2_ci | utf8mb4 | 244 | | Yes | 8 | PAD SPACE |
| utf8mb4_hr_0900_ai_ci | utf8mb4 | 275 | | Yes | 0 | NO PAD |
| utf8mb4_hr_0900_as_cs | utf8mb4 | 298 | | Yes | 0 | NO PAD |
| utf8mb4_hungarian_ci | utf8mb4 | 242 | | Yes | 8 | PAD SPACE |
| utf8mb4_hu_0900_ai_ci | utf8mb4 | 274 | | Yes | 0 | NO PAD |
| utf8mb4_hu_0900_as_cs | utf8mb4 | 297 | | Yes | 0 | NO PAD |
| utf8mb4_icelandic_ci | utf8mb4 | 225 | | Yes | 8 | PAD SPACE |
| utf8mb4_is_0900_ai_ci | utf8mb4 | 257 | | Yes | 0 | NO PAD |
| utf8mb4_is_0900_as_cs | utf8mb4 | 280 | | Yes | 0 | NO PAD |
| utf8mb4_ja_0900_as_cs | utf8mb4 | 303 | | Yes | 0 | NO PAD |
| utf8mb4_ja_0900_as_cs_ks | utf8mb4 | 304 | | Yes | 24 | NO PAD |
| utf8mb4_latvian_ci | utf8mb4 | 226 | | Yes | 8 | PAD SPACE |
| utf8mb4_la_0900_ai_ci | utf8mb4 | 271 | | Yes | 0 | NO PAD |
| utf8mb4_la_0900_as_cs | utf8mb4 | 294 | | Yes | 0 | NO PAD |
| utf8mb4_lithuanian_ci | utf8mb4 | 236 | | Yes | 8 | PAD SPACE |
| utf8mb4_lt_0900_ai_ci | utf8mb4 | 268 | | Yes | 0 | NO PAD |
| utf8mb4_lt_0900_as_cs | utf8mb4 | 291 | | Yes | 0 | NO PAD |
| utf8mb4_lv_0900_ai_ci | utf8mb4 | 258 | | Yes | 0 | NO PAD |
| utf8mb4_lv_0900_as_cs | utf8mb4 | 281 | | Yes | 0 | NO PAD |
| utf8mb4_persian_ci | utf8mb4 | 240 | | Yes | 8 | PAD SPACE |
| utf8mb4_pl_0900_ai_ci | utf8mb4 | 261 | | Yes | 0 | NO PAD |
| utf8mb4_pl_0900_as_cs | utf8mb4 | 284 | | Yes | 0 | NO PAD |
| utf8mb4_polish_ci | utf8mb4 | 229 | | Yes | 8 | PAD SPACE |
| utf8mb4_romanian_ci | utf8mb4 | 227 | | Yes | 8 | PAD SPACE |
| utf8mb4_roman_ci | utf8mb4 | 239 | | Yes | 8 | PAD SPACE |
| utf8mb4_ro_0900_ai_ci | utf8mb4 | 259 | | Yes | 0 | NO PAD |
| utf8mb4_ro_0900_as_cs | utf8mb4 | 282 | | Yes | 0 | NO PAD |
| utf8mb4_ru_0900_ai_ci | utf8mb4 | 306 | | Yes | 0 | NO PAD |
| utf8mb4_ru_0900_as_cs | utf8mb4 | 307 | | Yes | 0 | NO PAD |
| utf8mb4_sinhala_ci | utf8mb4 | 243 | | Yes | 8 | PAD SPACE |
| utf8mb4_sk_0900_ai_ci | utf8mb4 | 269 | | Yes | 0 | NO PAD |
| utf8mb4_sk_0900_as_cs | utf8mb4 | 292 | | Yes | 0 | NO PAD |
| utf8mb4_slovak_ci | utf8mb4 | 237 | | Yes | 8 | PAD SPACE |
| utf8mb4_slovenian_ci | utf8mb4 | 228 | | Yes | 8 | PAD SPACE |
| utf8mb4_sl_0900_ai_ci | utf8mb4 | 260 | | Yes | 0 | NO PAD |
| utf8mb4_sl_0900_as_cs | utf8mb4 | 283 | | Yes | 0 | NO PAD |
| utf8mb4_spanish2_ci | utf8mb4 | 238 | | Yes | 8 | PAD SPACE |
| utf8mb4_spanish_ci | utf8mb4 | 231 | | Yes | 8 | PAD SPACE |
| utf8mb4_sv_0900_ai_ci | utf8mb4 | 264 | | Yes | 0 | NO PAD |
| utf8mb4_sv_0900_as_cs | utf8mb4 | 287 | | Yes | 0 | NO PAD |
| utf8mb4_swedish_ci | utf8mb4 | 232 | | Yes | 8 | PAD SPACE |
| utf8mb4_tr_0900_ai_ci | utf8mb4 | 265 | | Yes | 0 | NO PAD |
| utf8mb4_tr_0900_as_cs | utf8mb4 | 288 | | Yes | 0 | NO PAD |
| utf8mb4_turkish_ci | utf8mb4 | 233 | | Yes | 8 | PAD SPACE |
| utf8mb4_unicode_520_ci | utf8mb4 | 246 | | Yes | 8 | PAD SPACE |
| utf8mb4_unicode_ci | utf8mb4 | 224 | | Yes | 8 | PAD SPACE |
| utf8mb4_vietnamese_ci | utf8mb4 | 247 | | Yes | 8 | PAD SPACE |
| utf8mb4_vi_0900_ai_ci | utf8mb4 | 277 | | Yes | 0 | NO PAD |
| utf8mb4_vi_0900_as_cs | utf8mb4 | 300 | | Yes | 0 | NO PAD |
| utf8mb4_zh_0900_as_cs | utf8mb4 | 308 | | Yes | 0 | NO PAD |
| utf8_bin | utf8 | 83 | | Yes | 1 | PAD SPACE |
| utf8_croatian_ci | utf8 | 213 | | Yes | 8 | PAD SPACE |
| utf8_czech_ci | utf8 | 202 | | Yes | 8 | PAD SPACE |
| utf8_danish_ci | utf8 | 203 | | Yes | 8 | PAD SPACE |
| utf8_esperanto_ci | utf8 | 209 | | Yes | 8 | PAD SPACE |
| utf8_estonian_ci | utf8 | 198 | | Yes | 8 | PAD SPACE |
| utf8_general_ci | utf8 | 33 | Yes | Yes | 1 | PAD SPACE |
| utf8_general_mysql500_ci | utf8 | 223 | | Yes | 1 | PAD SPACE |
| utf8_german2_ci | utf8 | 212 | | Yes | 8 | PAD SPACE |
| utf8_hungarian_ci | utf8 | 210 | | Yes | 8 | PAD SPACE |
| utf8_icelandic_ci | utf8 | 193 | | Yes | 8 | PAD SPACE |
| utf8_latvian_ci | utf8 | 194 | | Yes | 8 | PAD SPACE |
| utf8_lithuanian_ci | utf8 | 204 | | Yes | 8 | PAD SPACE |
| utf8_persian_ci | utf8 | 208 | | Yes | 8 | PAD SPACE |
| utf8_polish_ci | utf8 | 197 | | Yes | 8 | PAD SPACE |
| utf8_romanian_ci | utf8 | 195 | | Yes | 8 | PAD SPACE |
| utf8_roman_ci | utf8 | 207 | | Yes | 8 | PAD SPACE |
| utf8_sinhala_ci | utf8 | 211 | | Yes | 8 | PAD SPACE |
| utf8_slovak_ci | utf8 | 205 | | Yes | 8 | PAD SPACE |
| utf8_slovenian_ci | utf8 | 196 | | Yes | 8 | PAD SPACE |
| utf8_spanish2_ci | utf8 | 206 | | Yes | 8 | PAD SPACE |
| utf8_spanish_ci | utf8 | 199 | | Yes | 8 | PAD SPACE |
| utf8_swedish_ci | utf8 | 200 | | Yes | 8 | PAD SPACE |
| utf8_tolower_ci | utf8 | 76 | | Yes | 1 | PAD SPACE |
| utf8_turkish_ci | utf8 | 201 | | Yes | 8 | PAD SPACE |
| utf8_unicode_520_ci | utf8 | 214 | | Yes | 8 | PAD SPACE |
| utf8_unicode_ci | utf8 | 192 | | Yes | 8 | PAD SPACE |
| utf8_vietnamese_ci | utf8 | 215 | | Yes | 8 | PAD SPACE |
+----------------------------+----------+-----+---------+----------+---------+---------------+
272 rows in set (0.01 sec)
#utf8_general_ci 不区分大小写
#utf8_bin 区分大小写
查看当前使用的排序规则
bash
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+--------------------+
| Variable_name | Value |
+----------------------+--------------------+
| collation_connection | utf8mb4_0900_ai_ci |
| collation_database | utf8mb4_0900_ai_ci |
| collation_server | utf8mb4_0900_ai_ci |
+----------------------+--------------------+
3 rows in set (0.01 sec)
生产环境中,使用uf8mb4编码,使用默认排序规则
3.3管理数据库
3.3.1查看数据库列表
格式:
mysql
SHOW DATABASES;
范例:
bash
#默认这四个系统库,不能删除
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.01 sec)
3.3.2 创建数据库
格式:
bash
mysql> help create database;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_option] ...
create_option: [DEFAULT] {
CHARACTER SET [=] charset_name
| COLLATE [=] collation_name
| ENCRYPTION [=] {'Y' | 'N'}
}
CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.
URL: https://dev.mysql.com/doc/refman/8.0/en/create-database.html
格式:查询数据库创建语句
mysql
SHOW CREATE DATABASE DBNAME;
范例:
bash
mysql> create database testdb1;
Query OK, 1 row affected (0.00 sec)
#如果已存在,再次创建会报错
mysql> create database testdb1;
ERROR 1007 (HY000): Can't create database 'testdb1'; database exists
#不报错,但也没有创建,if not exists表示如果不存在则创建
mysql> create database if not exists testdb1;
Query OK, 1 row affected, 1 warning (0.00 sec)
#查看数据库列表
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| testdb1 |
+--------------------+
5 rows in set (0.01 sec)
#查看创建语句,包含默认字符集
mysql> SHOW CREATE DATABASE testdb1;
+----------+-----------------------------------------------------------------------------------------------------------------------------------+
| Database | Create Database |
+----------+-----------------------------------------------------------------------------------------------------------------------------------+
| testdb1 | CREATE DATABASE `testdb1` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */ |
+----------+-----------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
#创建时指定字符集
mysql> create database testdb2 DEFAULT CHARACTER SET latin1;
Query OK, 1 row affected (0.01 sec)
#查看创建语句
mysql> show create database testdb2;
+----------+-------------------------------------------------------------------------------------------------------+
| Database | Create Database |
+----------+-------------------------------------------------------------------------------------------------------+
| testdb2 | CREATE DATABASE `testdb2` /*!40100 DEFAULT CHARACTER SET latin1 */ /*!80016 DEFAULT ENCRYPTION='N' */ |
+----------+-------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
创建两个数据库,本质上是在硬盘上创建了两个目录
bash
[root@localhost ~]# ls -d /var/lib/mysql/testdb*
/var/lib/mysql/testdb1 /var/lib/mysql/testdb2
3.3.3 修改数据库
bash
mysql> help ALTER DATABASE;
Name: 'ALTER DATABASE'
Description:
Syntax:
ALTER {DATABASE | SCHEMA} [db_name]
alter_option ...
alter_option: {
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
| [DEFAULT] ENCRYPTION [=] {'Y' | 'N'}
| READ ONLY [=] {DEFAULT | 0 | 1}
}
范例:修改字符集
mysql
mysql> ALTER DATABASE testdb2 character set utf8mb4 COLLATE utf8mb4_0900_ai_ci;
Query OK, 1 row affected (0.00 sec)
mysql> show create database testdb2\G
*************************** 1. row ***************************
Database: testdb2
Create Database: CREATE DATABASE `testdb2` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */
1 row in set (0.00 sec)
3.3.4删除数据库
格式:
bash
mysql> help DROP DATABASE
Name: 'DROP DATABASE'
Description:
Syntax:
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
范例:
bash
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| testdb1 |
| testdb2 |
+--------------------+
6 rows in set (0.00 sec)
#删除数据库
mysql> DROP DATABASE testdb2;
Query OK, 0 rows affected (0.00 sec)
#删除不存在的库
mysql> DROP DATABASE testdb2;
ERROR 1008 (HY000): Can't drop database 'testdb2'; database doesn't exist
#加if exists判断
mysql> DROP DATABASE IF EXISTS testdb2;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| testdb1 |
+--------------------+
5 rows in set (0.00 sec)
#testdb2对应的目录已不存在
[root@localhost ~]# ls -d /var/lib/mysql/testdb* -d
/var/lib/mysql/testdb1
mysqladmin命令也可以创建和删除数据库
bash
#创建数据库db1
[root@localhost ~]# mysqladmin create db1
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| information_schema |
| mysql |
| performance_schema |
| sys |
| testdb1 |
+--------------------+
6 rows in set (0.00 sec)
#删除数据库db1
[root@localhost ~]# mysqladmin drop testdb1
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.
Do you really want to drop the 'testdb1' database [y/N] y #回答Y
Database "testdb1" dropped
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
3.4数据类型
MySQL 中定义数据字段的类型对你数据库的优化是非常重要的。
MySQL 支持多种类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。
对于任何一个数据表,每一行的每一列对应的元素都是下列数据类型的一种。
| 类型 | 关键字 |
|---|---|
| 整数类型 | TINYINT SMALLINT MEDIUMINT INT (INTEGER) BIGINT |
| 浮点类型 | FLOAT DOUBLE |
| 定点数类型 | DECIMAL |
| 位类型 | BIT |
| 日期时间类型 | YEAR TIME DATE DATETIME TIMESTAMP |
| 文本字符串类型 | CHAR VARCHAR TINYTEXT TEXT MEDIUMTEXT LONGTEXT |
| 枚举类型 | ENUM |
| 集合类型 | SET |
| 二进制字符串类型 | BINARY VARBINARY TINYBLOB BLOB MEDIUMBLOB LONGBLOB |
| JSON 类型 | JSON对象 JSON 数组 |
| 空间数据类型 (单值类型) | GEOMETRY POINT LINESTRING POLYGON |
| 空间数据类型 (集合类型) | MULTIPOINT MULTILINESTRING MULTIPOLYGON GEOMETRYCOLLECTION |
在常见数据表时,除了可以指定列的数据类型,还可以指定列的属性。
| 关键字 | 含义 |
|---|---|
| NULL | 数据列可包含 NULL 值 |
| NOT NULL | 数据列不允许包含 NULL 值 |
| DEFAULT | 默认值 |
| PRIMARY KEY | 主键 |
| AUTO_INCREMENT | 自动递增,适用于整数类型 |
| UNSIGNED | 无符号 |
| CHARACTER SET name | 指定一个字符集 |
3.4.1数值型
MySQL 支持所有标准 SQL 数值数据类型。
这些类型包括严格数值数据类型(INTEGER、SMALLINT、DECIMAL 和 NUMERIC),以及近似数值数据类型(FLOAT、REAL 和 DOUBLE PRECISION)。
关键字INT是INTEGER的同义词,关键字DEC是DECIMAL的同义词。
BIT数据类型保存位字段值,并且支持 MyISAM、MEMORY、InnoDB 和 BDB表。
作为 SQL 标准的扩展,MySQL 也支持整数类型 TINYINT、MEDIUMINT 和 BIGINT。下面的表显示了需要的每个整数类型的存储和范围。
| 类型 | 大小 | 范围(有符号) | 范围(无符号) | 用途 |
|---|---|---|---|---|
| TINYINT | 1 Bytes | (-128,127) | (0,255) | 小整数值 |
| SMALLINT | 2 Bytes | (-32 768,32 767) | (0,65 535) | 大整数值 |
| MEDIUMINT | 3 Bytes | (-8 388 608,8 388 607) | (0,16 777 215) | 大整数值 |
| INT或INTEGER | 4 Bytes | (-2 147 483 648,2 147 483 647) | (0,4 294 967 295) | 大整数值 |
| BIGINT | 8 Bytes | (-9 223 372 036 854 775 808 ,9 223 372 036 854 775 807) | (0,18 446 744 073 709 551 615) | 极大整数值 |
| FLOAT | 4 Bytes | (-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38) | 0,(1.175 494 351 E-38,3.402 823 466 E+38) | 单精度 浮点数值 |
| DOUBLE | 8 Bytes | (-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) | 0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) | 双精度 浮点数值 |
| DECIMAL | 对DECIMAL(M,D) ,如果M>D,为M+2否则为D+2 | 依赖于M和D的值 | 依赖于M和D的值 | 小数值 |
3.4.2日期和时间型
表示时间值的日期和时间类型为DATETIME、DATE、TIMESTAMP、TIME和YEAR。
每个时间类型有一个有效值范围和一个"零"值,当指定不合法的MySQL不能表示的值时使用"零"值。
TIMESTAMP类型有专有的自动更新特性,将在后面描述。
| 类型 | 大小 ( bytes) | 范围 | 格式 | 用途 |
|---|---|---|---|---|
| DATE | 3 | 1000-01-01/9999-12-31 | YYYY-MM-DD | 日期值 |
| TIME | 3 | '-838:59:59'/'838:59:59' | HH:MM:SS | 时间值或持续时间 |
| YEAR | 1 | 1901/2155 | YYYY | 年份值 |
| DATETIME | 8 | '1000-01-01 00:00:00' 到 '9999-12-31 23:59:59' | YYYY-MM-DD hh:mm:ss | 混合日期和时间值 |
| TIMESTAMP | 4 | '1970-01-01 00:00:01' UTC 到 '2038-01-19 03:14:07' UTC结束时间是第 2147483647 秒,北京时间 2038-1-19 11:14:07,格林尼治时间 2038年1月19日 凌晨 03:14:07 | YYYY-MM-DD hh:mm:ss | 混合日期和时间值,时间戳 |
3.4.3字符串类型
字符串类型指CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT、ENUM和SET。该节描述了这些类型如何工作以及如何在查询中使用这些类型。
| 类型 | 大小 | 用途 |
|---|---|---|
| CHAR | 0-255 bytes | 定长字符串 |
| VARCHAR | 0-65535 bytes | 变长字符串 |
| TINYBLOB | 0-255 bytes | 不超过 255 个字符的二进制字符串 |
| TINYTEXT | 0-255 bytes | 短文本字符串 |
| BLOB | 0-65 535 bytes | 二进制形式的长文本数据 |
| TEXT | 0-65 535 bytes | 长文本数据 |
| MEDIUMBLOB | 0-16 777 215 bytes | 二进制形式的中等长度文本数据 |
| MEDIUMTEXT | 0-16 777 215 bytes | 中等长度文本数据 |
| LONGBLOB | 0-4 294 967 295 bytes | 二进制形式的极大文本数据 |
| LONGTEXT | 0-4 294 967 295 bytes | 极大文本数据 |
注意:char(n) 和 varchar(n) 中括号中 n 代表字符的个数,并不代表字节个数,比如 CHAR(30) 就可以存储 30 个字符。
CHAR 和 VARCHAR 类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。
BINARY 和 VARBINARY 类似于 CHAR 和 VARCHAR,不同的是它们包含二进制字符串而不要非二进制字符串。也就是说,它们包含字节字符串而不是字符字符串。这说明它们没有字符集,并且排序和比较基于列值字节的数值值。
BLOB 是一个二进制大对象,可以容纳可变数量的数据。有 4 种 BLOB 类型:TINYBLOB、BLOB、MEDIUMBLOB 和 LONGBLOB。它们区别在于可容纳存储范围不同。
有 4 种 TEXT 类型:TINYTEXT、TEXT、MEDIUMTEXT 和 LONGTEXT。对应的这 4 种 BLOB 类型,可存储的最大长度不同,可根据实际情况选择。
3.5 DDL 语句
DDL语句主要用来操作数据库中的表。
同一个库中不同表可以使用不同的存储引擎,但建议使用同一种存储引擎。
3.5.1创建表
格式
bash
#帮助
mysql> help create table
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }
.....
直接创建
bash
CREATE TABLE [IF NOT EXISTS] 'tbl_name' (col1 type1 修饰符,col2 type2 修饰符,...)
#字段格式
col type1 #定义字段数据类型
PRIMARY KEY(col1,...) #将该字段设为主键
INDEX(col1,...) #设置为索引
UNIQUE KEY(COL1,...) #设置为联合主键
#表选项
ENGINE [=] engine_name
ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT}
范例
mysql
CREATE TABLE student (
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
age tinyint UNSIGNED,
#height DECIMAL(5,2),
gender ENUM('M','F') default 'M'
)ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
#选择数据库
mysql> use db1;
Database changed
#执行SQL语句
mysql> CREATE TABLE student (
-> id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> name VARCHAR(20) NOT NULL,
-> age tinyint UNSIGNED,
-> #height DECIMAL(5,2),
-> gender ENUM('M','F') default 'M'
-> )ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
Query OK, 0 rows affected (0.02 sec)
#查看
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
+---------------+
1 row in set (0.00 sec)
#查看结构
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#插入一条数据
mysql> insert student (name,age)values('xiaoming',20);
Query OK, 1 row affected (0.01 sec)
#查询表中的所有数据
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
#再次插入一条数据
mysql> insert student(name,age,gender)values('xiaohong',18,'f');
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
| 11 | xiaohong | 18 | F |
+----+----------+------+--------+
2 rows in set (0.00 sec)
通过查询现存表创建,新表会被直接插入查询而来的数据
范例
bash
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#查询其他表创建
mysql> create table student2 select name,age from student;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
#查看
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
+---------------+
2 rows in set (0.00 sec)
#查看结构
mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
#数据也复制过来了
mysql> select * from student2;
+----------+------+
| name | age |
+----------+------+
| xiaoming | 20 |
| xiaohong | 18 |
+----------+------+
2 rows in set (0.00 sec)
通过复制现存的表的表结构创建,但不复制数据
范例
mysql
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> create table student3 like student;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
mysql> desc student3;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> select * from student3;
Empty set (0.00 sec)
3.5.2查看表
格式
bash
mysql> help show tables
Name: 'SHOW TABLES'
Description:
Syntax:
SHOW [EXTENDED] [FULL] TABLES
[{FROM | IN} db_name]
[LIKE 'pattern' | WHERE expr]
列出数据库中的表
格式
bash
SHOW TABLES [FROM db_name]
范例
bash
#查看当前库中所有表
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
#查看指定库中的表
mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
查看建表语句
格式
bash
SHOW CREATE TABLE [db_name.]tbl_name
范例
bash
mysql> show create table student;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| student | CREATE TABLE `student` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` tinyint unsigned DEFAULT NULL,
`gender` enum('M','F') DEFAULT 'M',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
#查看指定数据库的数据表
mysql> show create table db1.student\G
*************************** 1. row ***************************
Table: student
Create Table: CREATE TABLE `student` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` tinyint unsigned DEFAULT NULL,
`gender` enum('M','F') DEFAULT 'M',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
查看表结构
格式
bash
DESC [db_name.]tbl_name
SHOW COLUMNS FROM [db_name.]tbl_name
范例
bash
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> show columns from student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
查看表状态
格式
bash
SHOW TABLE STATUS LIKE 'tbl_name'
范例
bash
mysql> SHOW TABLE STATUS LIKE 'student';
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| student | InnoDB | 10 | Dynamic | 2 | 8192 | 16384 | 0 | 0 | 0 | 12 | 2025-09-18 22:10:21 | 2025-09-18 22:24:45 | NULL | utf8mb4_0900_ai_ci | NULL | | |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
1 row in set (0.00 sec)
mysql> SHOW TABLE STATUS LIKE 'student'\G
*************************** 1. row ***************************
Name: student
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 12
Create_time: 2025-09-18 22:10:21
Update_time: 2025-09-18 22:24:45
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.01 sec)
#不能有库名
mysql> SHOW TABLE STATUS LIKE 'db1.student'\G
Empty set (0.00 sec)
查看库中所有表状态
格式
mysql
SHOW TABLE STATUS FROM db_name
范例
bash
mysql> SHOW TABLE STATUS FROM db1\G
*************************** 1. row ***************************
Name: student
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 12
Create_time: 2025-09-18 22:10:21
Update_time: 2025-09-18 22:24:45
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
*************************** 2. row ***************************
Name: student2
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2025-09-18 22:35:06
Update_time: 2025-09-18 22:35:06
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
*************************** 3. row ***************************
Name: student3
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 1
Create_time: 2025-09-18 22:49:14
Update_time: NULL
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
3 rows in set (0.01 sec)
查看当前MySQL服务支持的引擎
格式
mysql
SHOW ENGINES
范例
mysql
mysql> mysql> SHOW ENGINES;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment | Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES | YES | YES |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| MyISAM | YES | MyISAM storage engine | NO | NO | NO |
| MRG_MYISAM | YES | Collection of identical MyISAM tables | NO | NO | NO |
| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| CSV | YES | CSV storage engine | NO | NO | NO |
| ARCHIVE | YES | Archive storage engine | NO | NO | NO |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.01 sec)
mysql> SHOW ENGINES\G
*************************** 1. row ***************************
Engine: FEDERATED
Support: NO
Comment: Federated MySQL storage engine
Transactions: NULL
XA: NULL
Savepoints: NULL
*************************** 2. row ***************************
Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 3. row ***************************
Engine: InnoDB
Support: DEFAULT
Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
XA: YES
Savepoints: YES
*************************** 4. row ***************************
Engine: PERFORMANCE_SCHEMA
Support: YES
Comment: Performance Schema
Transactions: NO
XA: NO
Savepoints: NO
*************************** 5. row ***************************
Engine: MyISAM
Support: YES
Comment: MyISAM storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 6. row ***************************
Engine: MRG_MYISAM
Support: YES
Comment: Collection of identical MyISAM tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 7. row ***************************
Engine: BLACKHOLE
Support: YES
Comment: /dev/null storage engine (anything you write to it disappears)
Transactions: NO
XA: NO
Savepoints: NO
*************************** 8. row ***************************
Engine: CSV
Support: YES
Comment: CSV storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 9. row ***************************
Engine: ARCHIVE
Support: YES
Comment: Archive storage engine
Transactions: NO
XA: NO
Savepoints: NO
9 rows in set (0.00 sec)
3.5.3修改和删除表
mysql
ALTER TABLE tbl_name
[alter_option [, alter_option] ...]
[partition_options]
mysql
{ ADD COLUMN <列名> <类型>
| CHANGE COLUMN <旧列名> <新列名> <新列类型>
| ALTER COLUMN <列名> { SET DEFAULT <默认值>丨DROP DEFAULT }
| MODIFY COLUMN <列名> <类型>
| DROP COLUMN <列名>
| RENAME TO <新表名> }
范例
bash
#修改表名
mysql> ALTER TABLE student RENAME stu;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#添加表字段
mysql> ALTER TABLE stu ADD phone varchar(11) AFTER name;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| phone | varchar(11) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#修改字段类型
mysql> ALTER TABLE stu MODIFY phone int;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| phone | int | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#修改字段名称和类型
mysql> ALTER TABLE stu CHANGE COLUMN phone mobile char(11);
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| mobile | char(11) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#删除字段
mysql> ALTER TABLE stu DROP COLUMN mobile;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#修改表字符集
mysql> ALTER TABLE stu character SET utf8;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 1
#同时修改数据类型和字符集,只修改字符集,类型也不能少
mysql> ALTER TABLE stu CHANGE name name char(30) character set utf8;
Query OK, 2 rows affected, 1 warning (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 1
#设置字段默认值
mysql> alter table stu alter column gender set default 'M';
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
#添加字段和修改字段
mysql> ALTER TABLE stu ADD is_del bool DEFAULT false;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE stu modify is_del bool DEFAULT true;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
范例
bash
mysql> create table stu2 select * from stu;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
#添加主键
mysql> ALTER TABLE stu2 ADD PRIMARY KEY (id);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | PRI | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
#删除主键
mysql> ALTER TABLE stu2 DROP PRIMARY KEY;
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
删除表
格式
bash
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
范例
bash
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| stu2 |
| student2 |
| student3 |
+---------------+
4 rows in set (0.00 sec)
mysql> drop table student2;drop table db1.student3;
Query OK, 0 rows affected (0.01 sec)
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| stu2 |
+---------------+
2 rows in set (0.00 sec)
3.6 DML 语句
DML语句包括INSERT,UDPATE,DELETE
3.6.1插入数据
INSERT可以一次往表中插入一条或多条记录
格式
bash
mysql> help INSERT
Name: 'INSERT'
Description:
Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
{ {VALUES | VALUE} (value_list) [, (value_list)] ...
|
VALUES row_constructor_list
}
[AS row_alias[(col_alias [, col_alias] ...)]]
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[AS row_alias[(col_alias [, col_alias] ...)]]
SET assignment_list
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
[AS row_alias[(col_alias [, col_alias] ...)]]
{SELECT ... | TABLE table_name}
[ON DUPLICATE KEY UPDATE assignment_list]
简化格式
bash
INSERT tbl_name [(col1,...)] VALUES (val1,...),(val21,...)
范例
bash
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
+----+----------+------+--------+--------+
2 rows in set (0.00 sec)
#给出所有字段值(给出所有字段值,可以不用标明字段,只要顺序一一对应即可)
mysql> INSERT INTO stu VALUES(12,'xiaoli',19,'F',0);
Query OK, 1 row affected (0.01 sec)
#只给出部分字段值,因为有些字段值有默认值
mysql> INSERT INTO stu(name,age)VALUES('xiaozhou',20);
Query OK, 1 row affected (0.02 sec)
#一次插入多条
mysql> INSERT INTO stu (name,age)VALUES('test1',20),('test2',21),('test3',22);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
#有默认值的用默认值,没有默认值的用NULL值
mysql> INSERT stu (age,is_del)VALUES(23,0);
Query OK, 1 row affected (0.00 sec)
#查看
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | xiaoli | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
+----+----------+------+--------+--------+
8 rows in set (0.00 sec)
#如果记录不存在就新增,如果存在就更新
mysql> SELECT * FROM stu WHERE id=12;
+----+--------+------+--------+--------+
| id | name | age | gender | is_del |
+----+--------+------+--------+--------+
| 12 | xiaoli | 19 | F | 0 |
+----+--------+------+--------+--------+
1 row in set (0.00 sec)
mysql> INSERT INTO stu (id,name)VALUES(12,'zhangsan');
ERROR 1062 (23000): Duplicate entry '12' for key 'stu.PRIMARY'
mysql> INSERT INTO stu (id,name)VALUES(12,'zhangsan') ON DUPLICATE KEY UPDATE name='zhangsan';
Query OK, 2 rows affected (0.00 sec)
mysql> SELECT * FROM stu WHERE id=12;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 12 | zhangsan | 19 | F | 0 |
+----+----------+------+--------+--------+
1 row in set (0.00 sec)
#将查询结果当值插入
mysql> insert into stu (name,age,gender) select name,age,gender from stu where id=11;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | zhangsan | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
| 18 | xiaohong | 18 | F | 1 |
+----+----------+------+--------+--------+
9 rows in set (0.00 sec)
mysql> insert into stu (name,age,gender) select name,age,gender from stu where id in (11,12);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | zhangsan | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
| 18 | xiaohong | 18 | F | 1 |
| 19 | xiaohong | 18 | F | 1 |
| 20 | zhangsan | 19 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
3.6.2 更新数据
更新数据一定要加条件限制,没有条件则会更新表中所有记录。
mysql
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET assignment_list
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
范例
bash
#不加条件表示更新所有
mysql> UPDATE stu set age=30,gender='F';
Query OK, 11 rows affected (0.00 sec)
Rows matched: 11 Changed: 11 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 30 | F | 1 |
| 16 | test3 | 30 | F | 1 |
| 17 | NULL | 30 | F | 0 |
| 18 | xiaohong | 30 | F | 1 |
| 19 | xiaohong | 30 | F | 1 |
| 20 | zhangsan | 30 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#根据条件更新
mysql> update stu set age=31 WHERE id>15;
Query OK, 5 rows affected (0.01 sec)
Rows matched: 5 Changed: 5 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 30 | F | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 31 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#多个条件,满足任何一个条件都更新 OR 可以写成 ||
mysql> update stu set age=21,gender='M' where (id=15 OR name is null);
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 21 | M | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#多个条件满足,AND 可以写成 &&
mysql> update stu set age=22,gender='M' WHERE (id=17 AND name is null);
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 22 | M | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#NULL要写 IS NULL
mysql> update stu set gender='F' where name=NULL;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> update stu set gender='F' where name IS NULL;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
保证无法在没有条件的情况下更新所有
bash
-U, --i-am-a-dummy Synonym for option --safe-updates, -U.
[root@localhost ~]# mysql -U
#该配置还可以写到配置文件中
[root@localhost ~]# vim /etc/my.cnf.d/client.cnf
[client]
safe-updates
#无法完全更新
mysql> update stu set age=22;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
mysql> update stu set age=23 where name='test3';
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
#必须要指定主键
mysql> UPDATE stu SET age=23 WHERE id=17;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
3.6.3 删除数据
格式
bash
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
tbl_name[.*] [, tbl_name[.*]] ...
FROM table_references
[WHERE where_condition]
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
FROM tbl_name[.*] [, tbl_name[.*]] ...
USING table_references
[WHERE where_condition]
范例
bash
#查看全部数据
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#根据条件删除
mysql> delete from stu where id=10;
Query OK, 1 row affected (0.00 sec)
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
在直实生产环境中,一般不会对数据做物理删除,而是用字段来标记为逻辑删除,将对应字段值设为某个特定项(is_del ),(is_del=1)认为是己删除
bash
mysql> UPDATE stu SET is_del=1 WHERE id=11;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 1 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
清空表
bash
TRUNCATE TABLE tbl_name; #DDL语句,不支持事务,效率更高
DELETE FROM tbl_name; #DML语句
3.7 DQL 语句
格式
bash
mysql> help select
Name: 'SELECT'
Description:
Syntax:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr] ...
[into_option]
[FROM table_references
[PARTITION partition_list]]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
[HAVING where_condition]
[WINDOW window_name AS (window_spec)
[, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[into_option]
[FOR {UPDATE | SHARE}
[OF tbl_name [, tbl_name] ...]
[NOWAIT | SKIP LOCKED]
| LOCK IN SHARE MODE]
[into_option]
into_option: {
INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name] ...
}
说明
字段显示可以使用别名:col1 AS alias1,col2 AS alias2,...
WHERE子句:指明过滤条件以实现"选择"的功能
过滤条件:布尔型表达式
算术操作符:+,-,*,/,%
比较操作符:=,<=>(相等或都为空),<>,!=(非标准SQL,>,>=,<,<=
范围查询:BETWEEN min_num AND max_num
不连续的查询:IN(element1,element2,...)
空查询:IS NULL,,IS NOT NULL
DISTINCT去除重复行,范例:SELECT DISTINCT gender FROM students;
模糊查询:LIKE使用%表示任意长度的任意字符_表示任意单个字符
RLIKE:正则表达式,索引失效,不建议使用
REGEXP:匹配字符串可用正则表达式书写模式,同上
逻辑操作符:NOT,AND,OR,XOR
GROUPBY:根据指定的条件把查询结果进行"分组"以用于做"聚合"运算
常见聚合函数:count),sum(),max(),min(),avg(),注意:聚合函数不对null统计
HAVING:对分组聚合运算后的结果指定过滤条件
一旦分组group by,select语句后只跟分组的字段,聚合函数
ORDERBY:根据指定的字段对查询结果进行排序
升序:ASC
降序:DESC
LIMIT[offset,]row_count]:对查询的结果进行输出行数数量限制,跳过offset,显示row_count 行,offset默为值为0。
对查询结果中的数据请求施加"锁"
FOR UPDATE:写锁,独占或排它锁,只有一个读和写操作
LOCK IN SHARE MODE:读锁,共享锁,同时多个读操作
3.7.1单表操作
范例:查字符串和变量
bash
#直接查字符串
mysql> select 123;
+-----+
| 123 |
+-----+
| 123 |
+-----+
1 row in set (0.00 sec)
#指定别名
mysql> select 'gqd' as 'laogao';
+--------+
| laogao |
+--------+
| gqd |
+--------+
1 row in set (0.00 sec)
#数学计算
mysql> select 1+2*3;
+-------+
| 1+2*3 |
+-------+
| 7 |
+-------+
1 row in set (0.01 sec)
#查询变量
mysql> select @@port;
+--------+
| @@port |
+--------+
| 3306 |
+--------+
1 row in set (0.01 sec)
#查询函数
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2025-09-21 20:52:19 |
+---------------------+
1 row in set (0.00 sec)
范例:指定字段和查询条件
bash
#全表扫描
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 1 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
#查询指定字段
mysql> select id as 学号,name as 姓名,age as 年纪 from stu;
+--------+----------+--------+
| 学号 | 姓名 | 年纪 |
+--------+----------+--------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+--------+----------+--------+
10 rows in set (0.00 sec)
#根据条件查询
mysql> select id,name from stu where id=11;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
+----+----------+
1 row in set (0.00 sec)
#多条
mysql> select id,name from stu where id in(11,15,19);
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 15 | test2 |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.00 sec)
#and 可以写为 &&
mysql> select id,name from stu where id>=11 and id <14;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
+----+----------+
3 rows in set (0.00 sec)
#or 可以写为 ||
mysql> select id,name from stu where id<=12 or id>19;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 20 | zhangsan |
+----+----------+
3 rows in set (0.00 sec)
范例:NULL值
bash
mysql> select id,name,age from stu where name=NUll; #语法错误
Empty set (0.01 sec)
#null值
mysql> select id,name,age from stu where name IS NULL;
+----+------+------+
| id | name | age |
+----+------+------+
| 17 | NULL | 23 |
+----+------+------+
1 row in set (0.00 sec)
#非null值
mysql> select id,name,age from stu where name is not null;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
9 rows in set (0.00 sec)
范例:模糊匹配
bash
#以指定字符开头
mysql> select id,name from stu where name like 'x%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)
#以指定字符开头
mysql> select id,name from stu where name like 'xiao%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)
#以指定字符结尾
mysql> select id,name from stu where name like '%ng';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.00 sec)
#包含指定字符串
mysql> select id,name from stu where name like '%ou%';
+----+----------+
| id | name |
+----+----------+
| 13 | xiaozhou |
+----+----------+
1 row in set (0.00 sec)
#多个LIKE
mysql> select id,name from stu where name like '%n%' or name like '%i%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
6 rows in set (0.01 sec)
范例:区域间过滤
bash
#连续
mysql> select id,name from stu where id between 12 and 15;
+----+----------+
| id | name |
+----+----------+
| 12 | zhangsan |
| 13 | xiaozhou |
| 14 | test1 |
| 15 | test2 |
+----+----------+
4 rows in set (0.00 sec)
#取反
mysql> select id,name from stu where id not between 12 and 15;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
6 rows in set (0.00 sec)
#不连续
mysql> select id,name from stu where id in(12,15,19);
+----+----------+
| id | name |
+----+----------+
| 12 | zhangsan |
| 15 | test2 |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.01 sec)
#不连续取反
mysql> select id,name from stu where id not in (12,15,19);
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 14 | test1 |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 20 | zhangsan |
+----+----------+
7 rows in set (0.00 sec)
范例:统计和分组
bash
#统计表中的记录条数
mysql> select count(*) as total from stu;
+-------+
| total |
+-------+
| 10 |
+-------+
1 row in set (0.00 sec)
#name字段中有null,不统计
mysql> select count(name) from stu;
+-------------+
| count(name) |
+-------------+
| 9 |
+-------------+
1 row in set (0.00 sec)
mysql> select count(id) from stu;
+-----------+
| count(id) |
+-----------+
| 10 |
+-----------+
1 row in set (0.00 sec)
#最大值,最小值,平均值
mysql> select max(id),min(id),avg(age) from stu;
+---------+---------+----------+
| max(id) | min(id) | avg(age) |
+---------+---------+----------+
| 20 | 11 | 28.8000 |
+---------+---------+----------+
1 row in set (0.00 sec)
#求和
mysql> select sum(age) from stu;
+----------+
| sum(age) |
+----------+
| 288 |
+----------+
1 row in set (0.00 sec)
#分组统计
mysql> select sum(age),gender from stu group by gender;
+----------+--------+
| sum(age) | gender |
+----------+--------+
| 183 | F |
| 105 | M |
+----------+--------+
2 rows in set (0.00 sec)
#分组统计
mysql> select count(*),gender from stu group by gender;
+----------+--------+
| count(*) | gender |
+----------+--------+
| 6 | F |
| 4 | M |
+----------+--------+
2 rows in set (0.00 sec)
#分组带where条件
mysql> mysql> select count(*),max(id),avg(age),gender from stu where name is not null group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
| 6 | 19 | 30.5000 | F |
| 3 | 20 | 27.3333 | M |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)
#分组后过滤
mysql> select count(*) as total,max(id),avg(age),gender from stu where name is not null group by gender having total=3;
+-------+---------+----------+--------+
| total | max(id) | avg(age) | gender |
+-------+---------+----------+--------+
| 3 | 20 | 27.3333 | M |
+-------+---------+----------+--------+
1 row in set (0.00 sec)
#分组统计
mysql> select count(*),max(id),avg(age),gender from stu group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
| 6 | 19 | 30.5000 | F |
| 4 | 20 | 26.2500 | M |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)
mysql>
范例:排序
bash
#默认按ID升序排列
mysql> select id,name,age from stu;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
mysql> select id,name,age from stu order by id;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
mysql> select id,name,age from stu order by id asc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
#降序
mysql> select id,name,age from stu order by id desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 20 | zhangsan | 31 |
| 19 | xiaohong | 31 |
| 18 | xiaohong | 31 |
| 17 | NULL | 23 |
| 16 | test3 | 31 |
| 15 | test2 | 21 |
| 14 | test1 | 30 |
| 13 | xiaozhou | 30 |
| 12 | zhangsan | 30 |
| 11 | xiaohong | 30 |
+----+----------+------+
10 rows in set (0.00 sec)
#降序变升序
mysql> select id,name,age from stu order by -id desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
#用分组结果排序
mysql> select sum(age) sum_age,avg(age) avg_age,gender 性别 from stu where name is not null group by gender order by sum_age asc;
+---------+---------+--------+
| sum_age | avg_age | 性别 |
+---------+---------+--------+
| 82 | 27.3333 | M |
| 183 | 30.5000 | F |
+---------+---------+--------+
2 rows in set (0.00 sec)
mysql>
范例:去重
bash
mysql> select id,name,age from stu order by age desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 16 | test3 | 31 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 17 | NULL | 23 |
| 15 | test2 | 21 |
+----+----------+------+
10 rows in set (0.00 sec)
#去重
mysql> select distinct age from stu order by age desc;
+------+
| age |
+------+
| 31 |
| 30 |
| 23 |
| 21 |
+------+
4 rows in set (0.00 sec)
#去重
mysql> select distinct(age) from stu order by age desc;
+------+
| age |
+------+
| 31 |
| 30 |
| 23 |
| 21 |
+------+
4 rows in set (0.00 sec)
范例:分页
bash
mysql> select id,name from stu;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
| 14 | test1 |
| 15 | test2 |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
10 rows in set (0.00 sec)
#第一页,每页3条记录
# 0,3 跳过第0条从第一条开始,显示3条
mysql> select id,name from stu limit 0,3;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
+----+----------+
3 rows in set (0.00 sec)
#第二页,每页3条记录
mysql> select id,name from stu limit 3,3;
+----+-------+
| id | name |
+----+-------+
| 14 | test1 |
| 15 | test2 |
| 16 | test3 |
+----+-------+
3 rows in set (0.00 sec)
#第三页,每页3条记录
mysql> select id,name from stu limit 6,3;
+----+----------+
| id | name |
+----+----------+
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.01 sec)
3.8 MySQL用户管理
MySQL服务的账户是独立存在的,只用于MySQL服务的登录验证。
虚拟用户:给服务和应用使用的用户账号。
系统用户:Linux系统使用的用户账号
在MySQL服务中,用户组成包括用户名,主机,密码等。
Host指主机,表示只有在该主机上,才能使用对应的账号连接MySQL服务器,主机限制了账号可以登录的位置。用户名可以相同,主机也可以相同,用户名和主机组合起来才能标识一个唯一用户。
其它数据库系统,例如SQLServer,Oracle等都没有此限制,只要账号和密码能校验通过即可登录。这也是MySQL与其它数据库系统的一个不同之处。
Host可以写成主机名,IP地址,网段。可以用%,_来表示通配符,%表示任意长度的任意字符,_表示一个字符。
范例:
bash
#主机名
gqd@'mysql.laogao.cloud'
gqd@'localhost'
#IP地址
gqd@'10.0.0.110'
gqd@'172.16.10.110'
#网段
gqd@′10.0.0.0/255.255.0.0'
gqd@′172.16.10.0/255.255.255.0'
#通配符
gqd@′10.0.%.%
gqd@'172.16._.%'
MySQL8.0中默认没有可以远程登陆的用户
bash
mysql> use mysql;
#前三个是MySQL服务自身使用
mysql> select Host,User from user;
+-----------+------------------+
| Host | User |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
4 rows in set (0.00 sec)
#现在使用的是第四个
mysql> select user();
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
#也可以用status命令来查看
mysql> status
--------------
mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)
Connection id: 9
Current database: mysql
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 8.0.26 Source distribution
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8mb4
Db characterset: utf8mb4
Client characterset: utf8mb4
Conn. characterset: utf8mb4
UNIX socket: /var/lib/mysql/mysql.sock
Binary data as: Hexadecimal
Uptime: 38 min 22 sec
Threads: 2 Questions: 93 Slow queries: 0 Opens: 199 Flush tables: 3 Open tables: 118 Queries per second avg: 0.040
--------------
#无法在远程主机上连接当前主机的MySQL服务
#192.168.108.128是mysql主机ip地址
#另外一台电脑远程过来
[root@localhost ~]# mysql -uroot -h192.168.108.128 -p
Enter password:
ERROR 1130 (HY000): Host '192.168.108.132' is not allowed to connect to this MySQL server
创建用户:CREATE USER
bash
#格式
CREATE USER 'USERNAME'@'HOST' [IDENTIFIED BY 'password'];
#范例
create user test@'192.168.108.0/255.255.255.0' identified by '123456';
create user test2@'192.168.108.%' identified by '123456';
重命名用户:RENAME USER
bash
RENAME USER 'USERNAME'@'HOST' TO 'USERNAME'@'HOST';
删除用户:DROP USER
bash
DROP USER 'USERNAME'@'HOST'
#范例,删除gqd
DROP user test@'192.168.108.0/255.255.255.0'
DROP USER test2@'192.168.108.0.%';
修改密码
新版mysql中用户密码可以保存在mysql.user表的 authentication_string字段中,己经取消了password字段。
mariadb中某些版本 authentication_string,password字段共存,旧版以password字段为准,新版以authentication_string为准。
bash
#方式一
SET PASSWORD FOR 'user'@'host' = PASSWORD('password');
#mysql8.0中取消了PASSWORD方法
mysql> select PASSWORD('123456');
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 '('123456')' at line 1
#MariaDB中还有
#在MYSQL8.0中可以使用此写法
#MYSQL8.0中的密码是放在 mysql.user 表中 authentication_string 字段中,但MariaDB中还保留了PASSWORD字段
mysql> select Host,User,authentication_string FROM mysql.user;
+-----------+------------------+------------------------------------------------------------------------+
| Host | User | authentication_string |
+-----------+------------------+------------------------------------------------------------------------+
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | root | |
+-----------+------------------+------------------------------------------------------------------------+
4 rows in set (0.00 sec)
#更新密码
mysql> set password for root@'localhost'='123456';
Query OK, 0 rows affected (0.00 sec)
mysql> select Host,User,authentication_string FROM mysql.user;
+-----------+------------------+------------------------------------------------------------------------+
| Host | User | authentication_string |
+-----------+------------------+------------------------------------------------------------------------+
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | root | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+-----------+------------------+------------------------------------------------------------------------+
4 rows in set (0.00 sec)
mysql>
#方式二
语法:ALTER USER test@'%' IDENTIFIED BY '123456';
#此方法通用
mysql> ALTER USER root@'localhost' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)
#测试
[root@localhost ~]# mysql -uroot -p123456
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 16
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
#方法三
[root@localhost ~]# mysqladmin -uroot -p123456 password abcde
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@localhost ~]# mysql -uroot -pabcde
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 19
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
忘记密码
bash
#方式一,保留原有数据
#1 启动时添加指定项
--skip-grant-tables
--skip-networking
#2 使用UPDATE命令修改管理员密码
#3 移除配置项重启
#方式一范例
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
skip-grant-tables
skip-networking #MYSQL8.0不需要
[root@localhost ~]# systemctl restart mysqld.service
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
#步骤1
mysql> update mysql.user set authentication_string='' where user='root' and host='localhost';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
#步骤2
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
#再执行下面命令
mysql> alter user root@'localhost' identified by 'xiaomi';
Query OK, 0 rows affected (0.00 sec)
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
#pid-file=/run/mysqld/mysqld.pid
#skip-grant-tables
[root@localhost ~]# mysql -uroot -pxiaomi
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 9
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
范例:删库跑路之清空root密码方法
!!!学完就忘
bash
#方式二,会清除所有数据
#停止服务
[root@localhost ~]# systemctl stop mysqld.service
#删除数据目录下所有内容
[root@localhost ~]# rm -rf /var/lib/mysql/*
#重启服务,恢复空密码登陆
[root@localhost ~]# systemctl start mysqld.service
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
在当前MYSQL服务中添加用户
mysql
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> create user root@'192.168.108.1' identified by '123456'; #需要远程连接本mysql的客户端地址
Query OK, 0 rows affected (0.00 sec)
mysql> select Host,User from user;
+---------------+------------------+
| Host | User |
+---------------+------------------+
| 192.168.108.1 | root |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+---------------+------------------+
5 rows in set (0.00 sec)
到192.168.108.1(笔记本)操作

bash
#查看当前客户端连接时适用的用户名和主机
mysql> select user();
+--------------------+
| user() |
+--------------------+
| root@192.168.108.1 |
+--------------------+
1 row in set (0.00 sec)
#查看线程
mysql> show processlist;
+----+------+---------------------+-------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+---------------------+-------+---------+------+-------+------------------+
| 11 | root | localhost | mysql | Sleep | 360 | | NULL |
| 14 | root | 192.168.108.1:63707 | NULL | Query | 0 | init | show processlist |
+----+------+---------------------+-------+---------+------+-------+------------------+
2 rows in set (0.00 sec)
#查看数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)
#没有权限
mysql> use msyql;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.1' to database 'msyql'
mysql> create database db1;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.1' to database 'db1'
3.9权限管理和DCL语句
在MySQL服务中,新创建的用户仅仅只能连接,没有操作权限,需要配置相应的权限后才能使用。
3.9.1 权限类别
管理类
CREATE USER,FILE,SUPER,SHOW DATABASES,RELOAD,SHUTDOWN,REPLICATION SLAVE,REPLICATION CLIENT,LOCK TABLES,PROCESS,CREATE TEMPORARY TABLES
程序类针对FUNCTION、PROCEDURE、TRIGGER
CREATE,ALTER,DROP,EXCUTE
库和表级别针对DATABASE、TABLE
ALTER,CREATE,CREATE VIEW,DROP INDEX,SHOW VIEW,WITH GRANT OPTION(将自己获得的权限转赠给其他用户)
数据操作
SELECT,INSERT,DELETE,UPDATE
字段级别
SELECT(col1,coI2.,...),UPDATE(col1,col2,...),INSERT(col1,col2,...)
所有权限
ALL PRIVILEGES或ALL
3.9.2 授权
格式
bash
mysql> help grant
Name: 'GRANT'
Description:
Syntax:
GRANT
priv_type [(column_list)]
[, priv_type [(column_list)]] ...
ON [object_type] priv_level
TO user_or_role [, user_or_role] ...
[WITH GRANT OPTION]
[AS user
[WITH ROLE
DEFAULT
| NONE
| ALL
| ALL EXCEPT role [, role ] ...
| role [, role ] ...
#priv_type 要授予的权限ALL [PRIVILEGES]
#object_type 对象的类型TABLE|FUNCTION|PROCEDURE
#priv_level 范围 *|*.*|db_name.*|db_name.tbl_name|tbl_name|db_name.routine_name(指定库的函数,存储过程,触发器)
#with_option 选项
#GRANT OPTION 可以将自己的权限授权给其它账号
#MAX_QUERIES_PER_HOUR N 每小时最大查询次数
#MAX_UPDATES_PER_HOUR N 每小时最大更新次数
#MAX_CONNECTIONS_PER_HOUR N 每小时最大连接次数
#MAX_USER_CONNECTIONS N 最大用户连接数
#MAX_USER_CONNECTIONS 指的是瞬间的并发连接数,而MAX_CONNECTIONS_PER_HOUR指的是每小时累计的最大连接次数
#资源限制是对某一账号进行累计的,而不是对账号的一次连接进行累计的,当资源限制到达后,账号的任何一次相关操作都会被拒
范例:
bash
#只能查询,插入指定字段
GRANT SELECT(col1),INSERT(col1,col2) ON mydb.mytbl TO 'someuser'@'somehost';
#有指定库的所有权限
GRANT ALL ON wordpress.* TO wordpress@'10.0.0.%';
#授予所有权限
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.0.0.%' WITH GRANT OPTION;
#创建用户和授权同时执行的方式在MySQL8.0取消了
GRANT ALL ON wordpress.* TO wordpress@'192.168.108.%' IDENTIFIED BY 'huawei';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.108.%' IDENTIFIED BY 'huawei' WITH GRANT OPTION;
3.9.3 取消权限
格式
bash
REVOKE
priv_type [(column_list)]
[, priv_type [(column_list)]] ...
ON [object_type] priv_level
FROM user_or_role [, user_or_role] ...
范例
bash
REVOKE DELETE ON *.* FROM 'testuser'@'172.16.0.%';
REVOKE ALL ON *.* FROM'testuser'@'172.16.0.%';
3.9.4查看用户权限
格式
mysql
#查看指定用户权限
SHOW GRANTS FOR 'user'@'host';
#查看当前使用中的用户的权限
SHOW GRANTS FOR CURRENT_USER[()];
注意
- MariaDB服务进程启动时会读取mysql库中所有授权表至内存。
- GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效。
- 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:mysql>FLUSH PRIVILEGES。
范例
bash
#本地操作
#创建用户
mysql> create user 'root'@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.01 sec)
mysql> select host,user from mysql.user;
+---------------+------------------+
| host | user |
+---------------+------------------+
| 192.168.108.% | root |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+---------------+------------------+
5 rows in set (0.00 sec)
#查看新用户的权限,默认只有 USAGE 权限,只能连接
mysql> show grants for 'root'@'192.168.108.%';
+----------------------------------------------+
| Grants for root@192.168.108.% |
+----------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
+----------------------------------------------+
1 row in set (0.00 sec)
#远程连接,远程操作
[root@localhost ~]# mysql -uroot -p123456 -h192.168.108.128
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 14
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
#查看权限,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+----------------------------------------------+
| Grants for root@192.168.108.% |
+----------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
+----------------------------------------------+
1 row in set (0.00 sec)
#无权限创建,远程操作
mysql> create database db1;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.%' to database 'db1'
bash
#本地操作
mysql> create database db1;
mysql> create database db2;
mysql> use db1;
CREATE TABLE student (
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
age tinyint UNSIGNED,
#height DECIMAL(5,2),
gender ENUM('M','F') default 'M'
)ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
mysql> insert student (name,age)values('xiaoming',20);
#授权能查看 mysql 中的 user 表,本地操作
mysql> grant select on db1.student to root@'192.168.108.%';
Query OK, 0 rows affected (0.00 sec)
#远程用户再次刷新,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+-----------------------------------------------------------+
| Grants for root@192.168.108.% |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
| GRANT SELECT ON `db1`.`student` TO `root`@`192.168.108.%` |
+-----------------------------------------------------------+
2 rows in set (0.00 sec)
#能看到数据库,远程操作
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
#远程操作
mysql> use db1;
Database changed
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
+---------------+
1 row in set (0.00 sec)
#远程操作
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
#没有更新权限,远程操作
mysql> update student set age=25 where id=10;
ERROR 1142 (42000): UPDATE command denied to user 'root'@'192.168.108.1' for table 'student'
#没有删除权限,远程操作
mysql> delete from student where id=10;
ERROR 1142 (42000): DELETE command denied to user 'root'@'192.168.108.1' for table 'student'
#继续授权,本地操作
mysql> grant update,delete on db1.student to root@'192.168.108.%';
#再次查看,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+---------------------------------------------------------------------------+
| Grants for root@192.168.108.% |
+---------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
| GRANT SELECT, UPDATE, DELETE ON `db1`.`student` TO `root`@`192.168.108.%` |
+---------------------------------------------------------------------------+
2 rows in set (0.00 sec)
#测试,远程操作
mysql> update student set age=25 where id=10;
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 25 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
mysql> delete from student where id=10;
mysql> select * from student;
Empty set (0.00 sec)
范例
bash
#创建数据库,本地操作
mysql> create database eshop;
Query OK, 1 row affected (0.00 sec)
#创建用户,本地操作
mysql> create user eshoper@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
#授权,本地操作
mysql> grant all on eshop.* to eshoper@'192.168.108.%';
Query OK, 0 rows affected (0.00 sec)
#远程测试
C:\Users\69466>mysql -ueshoper -p123456 -h192.168.108.128
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 17
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2025, 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 |
+--------------------+
| eshop |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
#创建表
mysql> use eshop;
Database changed
mysql> create table product (id int,name varchar(10));
Query OK, 0 rows affected (0.10 sec)
mysql> show tables;
+-----------------+
| Tables_in_eshop |
+-----------------+
| product |
+-----------------+
1 row in set (0.00 sec)
3.10MySQL图形化远程管理工具
在MySQL数据库中创建用户并授权后,可以使用相关图形化工具进行远程的管理。
常见的图形化管理工具包括Navicat,SQLyog,DBbear等。
3.10.1 Navicat 工具
3.10.2 SQLyog 工具

3.11实现基于LAMP架构的开源网站
3.11.1 LAMP 架构说明
LAMP是指一组通常一起使用来运行动态网站的自由软件名称首字母的缩写。
- L是指Linux操作系统。
- A是指Apache,用来提供Web服务。
- M指MySQL,用来提供数据库服务。
- P指PHP,是动态网站的的一种开发语言。
LAMP是中小型动态网站的常见组合,虽然这些开放源代码程序本身并不是专门设计成同另几个程序一起工作的,但由于它们各自的特点和普遍性,使得这个组合在搭建动态网站这一领域开始流行起来。
3.11.2 PHP 简介
PHP:(Hypertext Preprocessor)超文本预处理器。


PHP是通用服务器端脚本编程语言,主要用于WEB开发实现动态WEB页面,也是最早实现将脚本嵌入HTML源码文档中的服务器端脚本语言之一。同时,PHP还提供了一个命令行接口,因此,其也可以在大多数系统上作为一个独立的SHELL来使用。Rasmus Lerdorf于1994年开始开发PHP,最初是一组被Rasmus Lerdorf称作"Personal Home PageTool"的Perl脚本,可以用于显示作者的简历并记录用户对其网站的访问。后来,Rasmus Lerdorf使用C语言将这些Perl脚本重写为CGI程序,还为其增加了运行Web forms的能力以及与数据库交互的特性,并将其重命名为"Personal Home Page/Forms Interpreter"或"PHP/FI"。此时,PHP/FI已经可以用于开发简单的动态WEB程序了,这即PHP1.0。1995年6月,Rasmus Lerdorf 把它的 PHP发布于comp.infosystems.www.authoring.cgi Usenet讨论组,从此PHP开始走进人们的视野。1997年,其2.0版本发布。
1997年,两名以色列程序员Zeev Suraski 和Andi Gutmans重写的PHP的分析器(parser)成为 PHP发展到3.0的基础,而且从此将PHP重命名为PHP:Hypertext Preprocessor。此后,这两名程序员开始重写整个PHP核心,并于1999年发布了Zend Engine1.0,这也意味着PHP 4.0的诞生。2004年7月,ZendEngine 2.0发布,由此也将PHP带入了PHP5时代。PHP5包含了许多重要的新特性,如增强的面向对象编程的支持、支持PDO(PHP Data Objects)扩展机制以及一系列对PHP性能的改进。
Zend Engine是开源的、PHP脚本语言的解释器,它最早是由以色列理工学院(Technion)的学生AndiGutmans和Zeev Suraski 所开发,Zend也正是此二人名字的合称。后来两人联合创立了ZendTechnologies公司。
Zend Engine1.0于1999年随PHP4发布,由C语言开发且经过高度优化,并能够做为PHP的后端模块使用。Zend Engine为PHP提供了内存和资源管理的功能以及其它的一些标准服务,其高性能、可靠性和可扩展性在促进PHP成为一种流行的语言方面发挥了重要作用。Zend Engine的出现将PHP代码的处理过程分成了两个阶段:首先是分析PHP代码并将其转换为称作Zend opcode的二进制格式opcode(类似Java的字节码),并将其存储于内存中;第二阶段是使用ZendEngine去执行这些转换后的Opcode。
PHP各种版本官方支持时间
https://www.php.net/supported-versions.php

/etc/php.ini配置文件格式
bash
[foo]: Section Header
directive = value
php.ini 配置参考文档
bash
php.ini的核心配置选项文档 http://php.net/manual/zh/ini.core.php
php.ini配置选项列表 http://php.net/manual/zh/ini.1ist.php
php常见配置项
bash
expose_php=On #响应报文显示首部字段x-powered-by:PHP/x.y.z,暴露php版本,建议为off
max_execution_time=30 #最长执行时间30s
memory_limit=128M #生产不够,可调大
display_errors=off #调试使用,不要打开,否则可能暴露重要信息
display_startup_errors=off #建议关闭
post_max_size=8M #最大上传数据大小,生产可能调大,比下面项大
upload_max_filesize=2M #最大上传文件,生产可能要调大
max_file_uploads=20 #同时上传最多文件数
date.timezone=Asia/shanghai #指定时区
short_open_tag=On #支持短标签
3.11.3实现博客项目
服务器配置(centos8)
| IP地址规划 | 作用 | 软件 |
|---|---|---|
| 192.168.108.100 | 提供WEB服务,PHP动态解析 | Apache,PHP |
| 192.168.108.101 | 提供数据库服务 | MySQL |
WordPress
WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。
官方网站
具体实现
bash
#在100上安装apapche和PHP
[root@web ~]# yum -y install httpd php php-mysqlnd php-json php-gd php-xml php-mbstring php-zip
[root@web ~]# php -v
PHP 7.2.24 (cli) (built: Oct 22 2019 08:28:36) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
#关闭防火墙
[root@web ~]# systemctl disable --now firewalld
#启动WEB服务
[root@web ~]# systemctl start httpd.service
#添加php测试页面
[root@web ~]# vim /var/www/html/test.php
<?php
phpinfo();
通过浏览器访问

bash
#下载wordpress 源码
[root@web ~]# cd /var/www/html/
[root@web html]# wget https://cn.wordpress.org/latest-zh_CN.zip
[root@web html]# unzip latest-zh_CN.zip
[root@web html]# ls
latest-zh_CN.zip test.php wordpress
#修改属主属组
[root@web html]# chown -R apache.apache wordpress/
#切换到101节点,创建数据库
[root@mysql ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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> create database wordpress;
Query OK, 1 row affected (0.02 sec)
#创建用户
mysql> create user 'wordpresser'@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.01 sec)
#授权
mysql> grant all on wordpress.* to 'wordpresser'@'192.168.108.%';
Query OK, 0 rows affected (0.01 sec)
为项目配置域名
bash
#在web服务器上配置域名指向的目录
[root@web ~]# vim /etc/httpd/conf.d/blog.gqd.cloud.conf
<VirtualHost *:80>
ServerName blog.gqd.cloud
DocumentRoot "/var/www/html/wordpress"
<Directory "/var/www/html/wordpress">
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#重启httpd
[root@web ~]# systemctl restart httpd
#在物理机上为域名设置解析
#在C:\windows\System32\drivers\etc\hosts添中如下行
192.168.108.100 blog.gqd.cloud
在页面上填写相关配置


配置完成后,通过浏览器访问
