4 SQL语言
4.1 关系型数据库的常见
数据库:database
表:table,行:row 列:column
索引:index
视图:view
用户:user
权限:privilege
存储过程:procedure
存储函数:function
触发器:trigger
事件调度器:event scheduler,任务计划
4.2 SQL语言的兴起与语法标准
20世纪70年代,IBM开发出SQL,用于DB2
1981年,IBM推出SQL/DS数据库
业内标准微软和Sybase的T-SQL,Oracle的PL/SQL
SQL作为关系型数据库所使用的标准语言,最初是基于IBM的实现在1986年被批准的。1987年,“国际标准化组织(ISO)”把ANSI(美国国家标准化组织) SQL作为国际标准
SQL:ANSI SQL,SQL-1986, SQL-1989, SQL-1992, SQL-1999, SQL-2003,SQL-2008, SQL-2011
4.2.1 SQL语言规范
注释:
SQL标准:
-- 注释内容 单行注释,注意有空格
/*注释内容*/ 多行注释
MySQL注释:
#
4.2.2 数据库对象和命名
数据库的组件(对象):
数据库、表、索引、视图、用户、存储过程、函数、触发器、事件调度器等
命名规则:
必须以字母开头,可包括数字和三个特殊字符(# _ $)
不要使用MySQL的保留字
同一database(Schema)下的对象不能同名
4.2.3 SQL语句分类
DDL: Data Defination Language 数据定义语言
CREATE,DROP,ALTER
DML: Data Manipulation Language 数据操纵语言
INSERT,DELETE,UPDATE
DQL:Data Query Language 数据查询语言
SELECT
DCL:Data Control Language 数据控制语言
GRANT,REVOKE,COMMIT,ROLLBACK
4.2.4 SQL语句构成
Keyword组成clause,多条clause组成语句
示例:
SELECT * #SELECT子句
FROM products #FROM子句
WHERE price>400 #WHERE子句
说明:一组SQL语句,由三个子句构成,SELECT,FROM和WHERE是关键字
数据库操作
获取SQL 命令使用帮助:
mysql> HELP KEYWORD;
4.2.5 字符集和排序
查看支持所有字符集:
utf8mb4支持表情包(大部分公司在用)
SHOW CHARACTER SET;
MariaDB [(none)]> SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+-----------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| euckr | EUC-KR Korean | euckr_korean_ci | 2 |
| koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| greek | ISO 8859-7 Greek | greek_general_ci | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |
| armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |
| utf8mb4 | UTF-8 Unicode | utf8mb4_general_ci | 4 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| utf16 | UTF-16 Unicode | utf16_general_ci | 4 |
| utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| utf32 | UTF-32 Unicode | utf32_general_ci | 4 |
| binary | Binary pseudo charset | binary | 1 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
+----------+-----------------------------+---------------------+--------+
40 rows in set (0.00 sec)
查看支持所有排序规则:
SHOW COLLATION;
设置服务器默认的字符集–>修改配置文件
vim /etc/my.cnf
[mysqld]
character-set-server=utf8mb4
设置mysql客户端默认的字符集
vim /etc/my.cnf
[mysql]
default-character-set=utf8mb4
4.3 管理数据库
4.3.1 创建数据库
CREATE DATABASE|SCHEMA [IF NOT EXISTS] 'DB_NAME';
CHARACTER SET 'character set name' COLLATE 'collate name'
MariaDB [(none)]> help create database;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name
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://mariadb.com/kb/en/create-database/
#查看所支持所有的字符集
MariaDB [(none)]> show variables like "character%";
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
MariaDB [(none)]> create database testdb1;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| db |
| information_schema |
| mysql |
| performance_schema |
| testdb1 |
+--------------------+
5 rows in set (0.00 sec)
#创建数据库就是在创建文件夹
[root@CentOS7 ~]#ll /var/lib/mysql/ -t
total 122936
drwx------ 2 mysql mysql 20 Nov 21 14:25 testdb1
drwx------ 2 mysql mysql 20 Nov 21 14:20 db
-rw-rw---- 1 mysql mysql 50331648 Nov 21 14:11 ib_logfile0
-rw-rw---- 1 mysql mysql 12582912 Nov 21 14:11 ibdata1
-rw-rw---- 1 mysql mysql 12582912 Nov 21 14:11 ibtmp1
-rw-rw---- 1 mysql mysql 5 Nov 21 14:11 CentOS7.pid
srwxrwxrwx 1 mysql mysql 0 Nov 21 14:11 mysql.sock
-rw-rw---- 1 mysql mysql 24576 Nov 21 14:11 tc.log
-rw-rw---- 1 mysql mysql 942 Nov 19 16:51 ib_buffer_pool
-rw-rw---- 1 mysql mysql 16384 Nov 19 16:51 aria_log.00000001
-rw-rw---- 1 mysql mysql 52 Nov 19 16:51 aria_log_control
-rw-rw---- 1 mysql mysql 0 Nov 19 11:36 multi-master.info
drwx------ 2 mysql mysql 20 Nov 19 11:33 performance_schema
drwx------ 2 mysql mysql 4096 Nov 19 11:33 mysql
-rw-rw---- 1 mysql mysql 50331648 Nov 19 11:33 ib_logfile1
#查看当初数据库创建时的命令和字符集
MariaDB [(none)]> show create database testdb1;
+----------+--------------------------------------------------------------------+
| Database | Create Database |
+----------+--------------------------------------------------------------------+
| testdb1 | CREATE DATABASE `testdb1` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+--------------------------------------------------------------------+
1 row in set (0.00 sec)
4.3.2 修改数据库
ALTER DATABASE DB_NAME character set utf8;
#修改数据库的字符集类型
MariaDB [(none)]> show create database testdb1;
+----------+--------------------------------------------------------------------+
| Database | Create Database |
+----------+--------------------------------------------------------------------+
| testdb1 | CREATE DATABASE `testdb1` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+--------------------------------------------------------------------+
1 row in set (0.00 sec)
MariaDB [(none)]> ALTER DATABASE testdb1 character set utf8mb4;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> show create database testdb1;
+----------+---------------------------------------------------------------------+
| Database | Create Database |
+----------+---------------------------------------------------------------------+
| testdb1 | CREATE DATABASE `testdb1` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ |
+----------+---------------------------------------------------------------------+
1 row in set (0.00 sec)
[root@CentOS7 ~]#cat /var/lib/mysql/testdb1/db.opt
default-character-set=utf8mb4 //修改
default-collation=utf8mb4_general_ci
4.3.3 删除数据库
DROP DATABASE|SCHEMA [IF EXISTS] 'DB_NAME';
MariaDB [(none)]> DROP DATABASe testdb1;
Query OK, 0 rows affected (0.01 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| db |
| information_schema |
| mysql |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)
[root@CentOS7 ~]#ll /var/lib/mysql/testdb1/
total 4
-rw-rw---- 1 mysql mysql 67 Nov 21 14:31 db.opt
[root@CentOS7 ~]#ll /var/lib/mysql/testdb1/
ls: cannot access /var/lib/mysql/testdb1/: No such file or directory
4.3.4 查看数据库列表
SHOW DATABASES;
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| db |
| information_schema |
| mysql |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)
4.4 数据类型
数据类型:
-
数据长什么样
-
数据需要多少空间来存放
数据类型
MySQL支持多种内置数据类型
- 数值类型
- 日期/时间类型
- 字符串(字符)类型
数据类型参考链接
https://dev.mysql.com/doc/refman/5.5/en/data-types.html
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U95o2uNO-1576071499576)(image-20191121094944022.png)]
选择正确的数据类型对于获得高性能至关重要,三大原则:
- 更小的通常更好,尽量使用可正确存储数据的最小数据类型
- 简单就好,简单数据类型的操作通常需要更少的CPU周期
- 尽量避免NULL,包含为NULL的列,对MySQL更难优化
4.4.1 整数型
-
tinyint(m) 1个字节 范围(-128~127)
-
smallint(m) 2个字节 范围(-32768~32767)
-
mediumint(m) 3个字节 范围(-8388608~8388607)
-
int(m) 4个字节 范围(-2147483648~2147483647)
-
bigint(m) 8个字节 范围(±9.22*10的18次方)
-
上述数据类型,如果加修饰符unsigned后,则最大值翻倍
如:tinyint unsigned的取值范围为(0~255) int(m)里的m是表示SELECT查询结果集中的显示宽度,并不影响实际的取值范围,规定了MySQL的一些交互工具(例如MySQL命令行客户端)用来显示字符的个数。对于存储和计算来说,Int(1)和Int(20)是相同的
-
BOOL,BOOLEAN:布尔型,是TINYINT(1)的同义词。zero值被视为假,非zero值视为真
4.4.2 浮点型(float和double),近似值
- float(m,d) 单精度浮点型 8位精度(4字节) m总个数,d小数位
- double(m,d) 双精度浮点型16位精度(8字节) m总个数,d小数位
设一个字段定义为float(6,3),如果插入一个数123.45678,实际数据库里存的是123.457,但总个数还以实际为准,即6位
4.4.3 定点数
- 在数据库中存放的是精确值,存为十进制
- decimal(m,d) 参数m<65 是总个数,d<30且 d<m 是小数位
- MySQL5.0和更高版本将数字打包保存到一个二进制字符串中(每4个字节存9个数字)。
例如:
decimal(18,9)小数点两边将各存储9个数字,一共使用9个字节:其中,小数点前的9个数字用4个字节,小数点后的9个数字用4个字节,小数点本身占1个字节
浮点类型在存储同样范围的值时,通常比decimal使用更少的空间。float使用4个字节存储。double占用8个字节
因为需要额外的空间和计算开销,所以应该尽量只在对小数进行精确计算时才使用decimal,例如存储财务数据。但在数据量比较大的时候,可以考虑使用bigint代替decimal
4.4.4 字符串(char,varchar,text)
- char(n) 固定长度,最多255个字符
- varchar(n) 可变长度,最多65535个字符
- tinytext 可变长度,最多255个字符
- text 可变长度,最多65535个字符
- mediumtext 可变长度,最多2的24次方-1个字符
- longtext 可变长度,最多2的32次方-1个字符
- BINARY(M) 固定长度,可存二进制或字符,长度为0-M字节
- VARBINARY(M) 可变长度,可存二进制或字符,允许长度为0-M字节
- 内建类型:ENUM枚举, SET集合
char和varchar:
参考:https://dev.mysql.com/doc/refman/8.0/en/char.html
Value | CHAR(4) | Storage Required | VARCHAR(4) | Storage Required |
---|---|---|---|---|
‘’ | ’ ’ | 4 bytes | ‘’ | 1 byte |
‘ab’ | 'ab ’ | 4 bytes | ‘ab’ | 3 bytes |
‘abcd’ | ‘abcd’ | 4 bytes | ‘abcd’ | 5 bytes |
‘abcdefgh’ | ‘abcd’ | 4 bytes | ‘abcd’ | 5 bytes |
1.char(n) 若存入字符数小于n,则以空格补于其后,查询之时再将空格去掉,所以char类型存储的字符串末尾不能有空格,varchar不限于此
2.char(n) 固定长度,char(4)不管是存入几个字符,都将占用4个字节,varchar是存入的实际字符数+1个字节(n< n>255),所以varchar(4),存入3个字符将占用4个字节
3.char类型的字符串检索速度要比varchar类型的快
varchar和text:
- varchar可指定n,text不能指定,内部存储varchar是存入的实际字符数+1个字节(n< n>255),text是实际字符数+2个字节。
- text类型不能有默认值
- varchar可直接创建索引,text创建索引要指定前多少个字符。varchar查询速度快于text
数据类型
4.4.5 二进制数据:BLOB
- BLOB和text存储方式不同,TEXT以文本方式存储,英文存储区分大小写,而Blob以二进制方式存储,不分大小写
- BLOB存储的数据只能整体读出,TEXT可以指定字符集,BLOB不用指定字符集
4.4.6 日期时间类型
- date 日期 ‘2008-12-2’
- time 时间 ‘12:25:36’
- datetime 日期时间 ‘2008-12-2 22:06:44’
- timestamp 自动存储记录修改时间
- YEAR(2), YEAR(4): 年份
- timestamp字段里的时间数据会随其他字段修改的时候自动刷新,这个数据类型的字段可以存放这条记录最后被修改的时间
4.4.7 修饰符
适用所有类型的修饰符:
- NULL 数据列可包含NULL值
- NOT NULL 数据列不允许包含NULL值
- DEFAULT 默认值
- PRIMARY KEY 主键
- UNIQUE KEY 唯一键
-
CHARACTER SET name 指定一个字符集(一般都是统一的字符集比较正常)
适用数值型的修饰符
- AUTO_INCREMENT 自动递增,适用于整数类型
- UNSIGNED 无符号
4.5 数据表DDL语句
- 表:二维关系
- 设计表:遵循规范
- 定义:字段,索引
- 字段:字段名,字段数据类型,修饰符
- 约束,索引:应该创建在经常用作查询条件的字段上
4.5.1 创建表
创建表:
CREATE TABLE
获取帮助:
HELP CREATE TABLE;
创建表的方法
(1) 直接创建
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}
注意:
- Storage Engine是指表类型,也即在表创建时指明其使用的存储引擎
- 同一库中不同表可以使用不同的存储引擎
- 同一个库中表建议要使用同一种存储引擎类型
范例
CREATE TABLE student (id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,name
VARCHAR(20) NOT NULL,age tinyint UNSIGNED);
DESC students;
CREATE TABLE employee (id int UNSIGNED NOT NULL ,name VARCHAR(20) NOT NULL,age
tinyint UNSIGNED,PRIMARY KEY(id,name));
MariaDB [(none)]> use db;
Database changed
MariaDB [db]> create table test ( id int unsigned auto_increment primary key,name varchar(10) not null,mobile char(11) not null);
Query OK, 0 rows affected (0.01 sec)
MariaDB [db]> desc test;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(10) | NO | | NULL | |
| mobile | char(11) | NO | | NULL | |
+--------+------------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
[root@CentOS7 ~]#mysql < hellodb_innodb.sql -p //导入数据库文件
Enter password:
[root@CentOS7 ~]#mysql -p //登陆客户端
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 15
Server version: 10.2.29-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show databases; //查看数据库
+--------------------+
| Database |
+--------------------+
| db |
| hellodb |
| information_schema |
| mysql |
| performance_schema |
+--------------------+
5 rows in set (0.00 sec)
MariaDB [(none)]> use hellodb; //切换到hellodb数据库;
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
MariaDB [hellodb]> show tables; //查看hellodb数据库中的数据表
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes |
| coc |
| courses |
| scores |
| students |
| teachers |
| toc |
+-------------------+
7 rows in set (0.00 sec)
MariaDB [hellodb]> desc students; //查看表students的描述;
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| StuID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)
(2) 通过查询现存表创建;新表会被直接插入查询而来的数据–>克隆旧的数据表,属性不是完全一样。
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options]
[partition_options] select_statement
*****************************************************************************************
MariaDB [hellodb]> create table newstudents select * from students; //以旧表常见克隆
Query OK, 25 rows affected (0.00 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc newstudents; //查看新表结构
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
MariaDB [hellodb]> desc students; //查看旧表结构
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| StuID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
MariaDB [hellodb]> select * from newstudents;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 3 | Xie Yanke | 53 | M | 2 | 16 |
| 4 | Ding Dian | 32 | M | 4 | 4 |
| 5 | Yu Yutong | 26 | M | 3 | 1 |
| 6 | Shi Qing | 46 | M | 5 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
(3) 通过复制现存的表的表结构创建,但不复制数据
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name { LIKE old_tbl_name | (LIKE
old_tbl_name) }
*****************************************************************************************
MariaDB [hellodb]> create table news3 like students; //克隆表结构
Query OK, 0 rows affected (0.01 sec)
MariaDB [hellodb]> desc news3;
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| StuID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)
MariaDB [hellodb]> select * from news3; //不复制数据
Empty set (0.00 sec)
4.5.2 表查看
查看支持的engine类型
SHOW ENGINES;
查看表:
SHOW TABLES [FROM db_name]
—————————————————————————————————————————————————————————————————————————————————————————
MariaDB [hellodb]> show tables from hellodb;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes |
| coc |
| courses |
| news3 |
| newstudents |
| scores |
| students |
| teachers |
| toc |
+-------------------+
9 rows in set (0.00 sec)
查看表结构:
DESC [db_name.]tb_name
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MariaDB [hellodb]> DESC students;
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| StuID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
SHOW COLUMNS FROM [db_name.]tb_name;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MariaDB [hellodb]> SHOW COLUMNS FROM students;
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| StuID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
查看表创建命令:
SHOW CREATE TABLE tbl_name
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MariaDB [hellodb]> SHOW CREATE TABLE students\G;
*************************** 1. row ***************************
Table: students
Create Table: CREATE TABLE `students` (
`StuID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL, \\enum 数据类型枚举。
`ClassID` tinyint(3) unsigned DEFAULT NULL,
`TeacherID` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`StuID`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
ERROR: No query specified
MariaDB [hellodb]> SHOW CREATE TABLE newstudents\G;
*************************** 1. row ***************************
Table: newstudents
Create Table: CREATE TABLE `newstudents` (
`StuID` int(10) unsigned NOT NULL DEFAULT 0,
`Name` varchar(50) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
`ClassID` tinyint(3) unsigned DEFAULT NULL,
`TeacherID` int(10) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
ERROR: No query specified
查看表状态:
SHOW TABLE STATUS LIKE 'tbl_name'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MariaDB [hellodb]> SHOW TABLE STATUS LIKE 'students'\G;
*************************** 1. row ***************************
Name: students
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 25
Avg_row_length: 655
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 26
Create_time: 2019-11-21 14:56:13
Update_time: 2019-11-21 14:56:13
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
查看库中所有表状态
SHOW TABLE STATUS FROM db_name
4.5.3 修改和删除表
删除表
DROP TABLE [IF EXISTS] 'tbl_name';
*****************************************************************************************
MariaDB [hellodb]> drop table newstudents;
Query OK, 0 rows affected (0.00 sec)
MariaDB [hellodb]> show tables ;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes |
| coc |
| courses |
| news3 |
| scores |
| students |
| teachers |
| toc |
+-------------------+
8 rows in set (0.01 sec)
修改表
ALTER TABLE 'tbl_name'
#字段:
#添加字段:add
ADD col1 data_type [FIRST|AFTER col_name]
#删除字段:drop
#修改字段:
alter(默认值), change(字段名), modify(字段属性)
查看修改表帮助
Help ALTER TABLE
修改表范例
MariaDB [hellodb]> create table news2 select * from students;
Query OK, 25 rows affected (0.01 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc news2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
MariaDB [hellodb]> select * from news2;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 3 | Xie Yanke | 53 | M | 2 | 16 |
| 4 | Ding Dian | 32 | M | 4 | 4 |
| 5 | Yu Yutong | 26 | M | 3 | 1 |
| 6 | Shi Qing | 46 | M | 5 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
—————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE students RENAME s1;
MariaDB [hellodb]> ALTER TABLE news2 RENAME students2;
Query OK, 0 rows affected (0.02 sec)
MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes |
| coc |
| courses |
| news3 |
| scores |
| students |
| students2 |
| teachers |
| toc |
+-------------------+
9 rows in set (0.00 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 ADD phone varchar(11) AFTER name;
MariaDB [hellodb]> ALTER TABLE students2 ADD phone varchar(11) AFTER name;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> select * from students2;
+-------+---------------+-------+-----+--------+---------+-----------+
| StuID | Name | phone | Age | Gender | ClassID | TeacherID |
+-------+---------------+-------+-----+--------+---------+-----------+
| 1 | Shi Zhongyu | NULL | 22 | M | 2 | 3 |
| 2 | Shi Potian | NULL | 22 | M | 1 | 7 |
| 3 | Xie Yanke | NULL | 53 | M | 2 | 16 |
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 MODIFY phone int;
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| phone | varchar(11) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
MariaDB [hellodb]> alter table students2 modify phone int;
Query OK, 25 rows affected (0.08 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| phone | int(11) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 CHANGE COLUMN phone mobile char(11);
MariaDB [hellodb]> ALTER TABLE students2 CHANGE COLUMN phone mobile char(11);
Query OK, 25 rows affected (0.02 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| mobile | char(11) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 DROP COLUMN mobile;
MariaDB [hellodb]> ALTER TABLE students2 DROP COLUMN mobile;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| Name | varchar(50) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 character set utf8;
MariaDB [hellodb]> alter table students2 character set utf8;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> show table status like 'students2'\G;
*************************** 1. row ***************************
Name: students2
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 25
Avg_row_length: 655
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2019-11-21 15:39:41
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE s1 change name name varchar(20) character set utf8;
MariaDB [hellodb]> ALTER TABLE students2 change name name varchar(20) primary key ;
Query OK, 25 rows affected (0.03 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| name | varchar(20) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE students ADD gender ENUM('m','f');
MariaDB [hellodb]> ALTER TABLE students2 ADD gend ENUM('m','f');
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| name | varchar(20) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
| gend | enum('m','f') | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
MariaDB [hellodb]> select * from students2;
+-------+---------------+-----+--------+---------+-----------+------+
| StuID | name | Age | Gender | ClassID | TeacherID | gend |
+-------+---------------+-----+--------+---------+-----------+------+
| 20 | Diao Chan | 19 | F | 7 | NULL | NULL |
| 4 | Ding Dian | 32 | M | 4 | 4 | NULL |
| 15 | Duan Yu | 19 | M | 4 | NULL | NULL |
————————————————————————————————————————————————————————————————————————————————————————
ALETR TABLE students CHANGE id sid int UNSIGNED NOT NULL PRIMARY KEY;
MariaDB [hellodb]> ALTER TABLE students2 CHANGE StuID sid int(10) UNSIGNED NOT NULL PRIMARY KEY;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> DESC students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| sid | int(10) unsigned | NO | PRI | NULL | |
| name | varchar(20) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
| gend | enum('m','f') | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE students drop primary key ;
MariaDB [hellodb]> ALTER TABLE students2 drop primary key ;
Query OK, 25 rows affected (0.02 sec)
Records: 25 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| StuID | int(10) unsigned | NO | | 0 | |
| name | varchar(20) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
| gend | enum('m','f') | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
7 rows in set (0.01 sec)
————————————————————————————————————————————————————————————————————————————————————————
ALTER TABLE students DROP age;
MariaDB [hellodb]> ALTER TABLE students2 DROP age;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [hellodb]> DESC students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| sid | int(10) unsigned | NO | PRI | NULL | |
| name | varchar(20) | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
| gend | enum('m','f') | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
4.6 DML语句(数据库操作语言)
DML: INSERT, DELETE, UPDATE
4.6.1 INSERT 语句(增)
功能:一次插入一行或多行数据
语法
INSERT [L OW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE #如果重复更新之
col_name=expr
[, col_name=expr] ... ]
*****************************************************************************************
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
*****************************************************************************************
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
简化写法:
INSERT tbl_name [(col1,...)] VALUES (val1,...), (val21,...)
| 25 | Sun Dasheng | 100 | M | NULL | NULL |
| 26 | nanchen | 20 | F | 3 | 3 |
+-------+---------------+-----+--------+---------+-----------+
26 rows in set (0.00 sec)
MariaDB [hellodb]> insert into students values(26,'nanchen',20,'F',3,3); \\省略字段名
*****************************************************************************************
| 26 | nanchen | 20 | F | 3 | 3 |
| 27 | sanhai | 35 | M | NULL | NULL |
+-------+---------------+-----+--------+---------+-----------+
27 rows in set (0.00 sec)
MariaDB [hellodb]> insert into students(name,age,gender) values('sanhai',35,'M');添加特定字段的数值
*****************************************************************************************
| 26 | nanchen | 20 | F | 3 | 3 |
| 27 | sanhai | 35 | M | NULL | NULL |
| 28 | meichaofeng | 33 | M | NULL | NULL |
+-------+---------------+-----+--------+---------+-----------+
28 rows in set (0.00 sec)
MariaDB [hellodb]> insert into students set name='meichaofeng',age=33,gender='M';
*****************************************************************************************
| 27 | sanhai | 35 | M | NULL | NULL |
| 28 | meichaofeng | 33 | M | NULL | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
+-------+---------------+-----+--------+---------+-----------+
32 rows in set (0.00 sec)
MariaDB [hellodb]> insert students(name,classid,gender,age) select name,age,gender,18 from teachers;
第三种语法添加记录(批量导入)--也可以跨数据库导入数据(form database.table)。值类型是字符串要用''引起来
4.6.2 UPDATE 语句(改)
语法:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
*****************************************************************************************
| 36 | Song Jiang | 32 | M | 2 | 1 |
| 37 | Zhang Sanfeng | 94 | M | NULL | NULL |
| 38 | Miejue Shitai | 77 | F | NULL | NULL |
| 39 | Lin Chaoying | 93 | F | NULL | NULL |
+-------+---------------+-----+--------+---------+-----------+
36 rows in set (0.00 sec)
MariaDB [hellodb]> update students set age=32,classid=2,teacherid=1 where stuid=36;
注意:一定要有限制条件,否则将修改所有行的指定字段
可利用mysql 选项避免此错误
mysql -U | --safe-updates| --i-am-a-dummy
[root@CentOS7 ~]#vim /etc/my.cnf.d/mysql-clients.cnf //修改配置文件,避免误操作。
#
# These groups are read by MariaDB command-line tools
# Use it for options that affect only one utility
#
[mysql]
safe-updates
*****************************************************************************************
MariaDB [hellodb]> update students set age=32,classid=2,teacherid=1;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
4.6.3 DELETE语句(删)
语法:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
可先排序再指定删除的行数
*****************************************************************************************
| 22 | Xiao Qiao | F | 1 | NULL | NULL |
| 23 | Ma Chao | M | 4 | NULL | NULL |
+-----+---------------+--------+---------+-----------+------+
23 rows in set (0.00 sec)
MariaDB [hellodb]> delete from students2 where sid=24;
注意:一定要有限制条件,否则将清空表中的所有数据
如果想清空表,保留表结构,也可以使用下面语句
TRUNCATE TABLE tbl_name;
*****************************************************************************************
MariaDB [hellodb]> TRUNCATE TABLE students2;
Query OK, 0 rows affected (0.02 sec)
MariaDB [hellodb]> select * from students2;
Empty set (0.00 sec)
MariaDB [hellodb]> desc students2;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| sid | int(10) unsigned | NO | PRI | NULL | |
| name | varchar(20) | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
| ClassID | tinyint(3) unsigned | YES | | NULL | |
| TeacherID | int(10) unsigned | YES | | NULL | |
| gend | enum('m','f') | YES | | NULL | |
+-----------+---------------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
4.7 DQL语句(数据库查询)
4.7.1 单表操作
语法:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[SQL_CACHE | SQL_NO_CACHE]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[FOR UPDATE | LOCK IN SHARE MODE]
说明:
-
字段显示可以使用别名:
###### col1 AS alias1, col2 AS alias2, ... ```sql MariaDB [hellodb]> select name 姓名,age 年龄 from students; +---------------+--------+ | 姓名 | 年龄 | +---------------+--------+ | Shi Zhongyu | 22 | | Shi Potian | 22 | | Xie Yanke | 53 | MariaDB [hellodb]> select name,age from students; +---------------+-----+ | name | age | +---------------+-----+ | Shi Zhongyu | 22 | | Shi Potian | 22 | | Xie Yanke | 53 | ```
-
WHERE子句:指明过滤条件以实现“选择”的功能:
```sql MariaDB [hellodb]> select 2*5+3 from teachers; +-------+ | 2*5+3 | +-------+ | 13 | | 13 | | 13 | | 13 | +-------+ 4 rows in set (0.00 sec) ```
```SQL MariaDB [hellodb]> select * from students where gender <> 'F'; +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 1 | Shi Zhongyu | 22 | M | 2 | 3 | | 2 | Shi Potian | 22 | M | 1 | 7 | | 3 | Xie Yanke | 53 | M | 2 | 16 | | 4 | Ding Dian | 32 | M | 4 | 4 | MariaDB [hellodb]> select * from students where STUID < 10; +-------+--------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+--------------+-----+--------+---------+-----------+ | 1 | Shi Zhongyu | 22 | M | 2 | 3 | | 2 | Shi Potian | 22 | M | 1 | 7 | | 3 | Xie Yanke | 53 | M | 2 | 16 | | 4 | Ding Dian | 32 | M | 4 | 4 | | 5 | Yu Yutong | 26 | M | 3 | 1 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 7 | Xi Ren | 19 | F | 3 | NULL | | 8 | Lin Daiyu | 17 | F | 7 | NULL | | 9 | Ren Yingying | 20 | F | 6 | NULL | +-------+--------------+-----+--------+---------+-----------+ ```
``` MariaDB [hellodb]> select * from students where AGE > 30 AND AGE < 50; +-------+--------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+--------------+-----+--------+---------+-----------+ | 4 | Ding Dian | 32 | M | 4 | 4 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 13 | Tian Boguang | 33 | M | 2 | NULL | | 26 | nanchen | 32 | F | 2 | 1 | | 27 | sanhai | 35 | M | NULL | NULL | | 28 | meichaofeng | 33 | M | NULL | NULL | | 36 | Song Jiang | 32 | M | 2 | 1 | +-------+--------------+-----+--------+---------+-----------+ MariaDB [hellodb]> select * from students where AGE BETWEEN 30 AND 50; +-------+--------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+--------------+-----+--------+---------+-----------+ | 4 | Ding Dian | 32 | M | 4 | 4 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 13 | Tian Boguang | 33 | M | 2 | NULL | | 26 | nanchen | 32 | F | 2 | 1 | | 27 | sanhai | 35 | M | NULL | NULL | | 28 | meichaofeng | 33 | M | NULL | NULL | | 36 | Song Jiang | 32 | M | 2 | 1 | +-------+--------------+-----+--------+---------+-----------+ 7 rows in set (0.00 sec) ```
```sql MariaDB [hellodb]> select * from students where classid in (1,3,6); +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 2 | Shi Potian | 22 | M | 1 | 7 | | 5 | Yu Yutong | 26 | M | 3 | 1 | | 7 | Xi Ren | 19 | F | 3 | NULL | | 9 | Ren Yingying | 20 | F | 6 | NULL | | 10 | Yue Lingshan | 19 | F | 3 | NULL | | 11 | Yuan Chengzhi | 23 | M | 6 | NULL | | 12 | Wen Qingqing | 19 | F | 1 | NULL | | 14 | Lu Wushuang | 17 | F | 3 | NULL | | 16 | Xu Zhu | 21 | M | 1 | NULL | | 19 | Xue Baochai | 18 | F | 6 | NULL | | 21 | Huang Yueying | 22 | F | 6 | NULL | | 22 | Xiao Qiao | 20 | F | 1 | NULL | +-------+---------------+-----+--------+---------+-----------+ 12 rows in set (0.00 sec) ```
```SQL MariaDB [hellodb]> select * from students where classid is null; +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 24 | Xu Xian | 27 | M | NULL | NULL | | 25 | Sun Dasheng | 100 | M | NULL | NULL | | 27 | sanhai | 35 | M | NULL | NULL | | 28 | meichaofeng | 33 | M | NULL | NULL | | 37 | Zhang Sanfeng | 94 | M | NULL | NULL | | 38 | Miejue Shitai | 77 | F | NULL | NULL | | 39 | Lin Chaoying | 93 | F | NULL | NULL | +-------+---------------+-----+--------+---------+-----------+ ```
```sql MariaDB [hellodb]> select * from students where TeacherID is not null;; +-------+-------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+-------------+-----+--------+---------+-----------+ | 1 | Shi Zhongyu | 22 | M | 2 | 3 | | 2 | Shi Potian | 22 | M | 1 | 7 | | 3 | Xie Yanke | 53 | M | 2 | 16 | | 4 | Ding Dian | 32 | M | 4 | 4 | | 5 | Yu Yutong | 26 | M | 3 | 1 | | 26 | nanchen | 32 | F | 2 | 1 | | 36 | Song Jiang | 32 | M | 2 | 1 | +-------+-------------+-----+--------+---------+-----------+ ```
```sql MariaDB [hellodb]> select distinct classid from students; +---------+ | classid | +---------+ | 2 | | 1 | | 4 | | 3 | | 5 | | 7 | | 6 | | NULL | | 45 | | 94 | | 77 | | 93 | +---------+ 12 rows in set (0.00 sec) ```
```sql MariaDB [hellodb]> select * from students where name like 's%'; +-------+-------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+-------------+-----+--------+---------+-----------+ | 1 | Shi Zhongyu | 22 | M | 2 | 3 | | 2 | Shi Potian | 22 | M | 1 | 7 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 25 | Sun Dasheng | 100 | M | NULL | NULL | | 27 | sanhai | 35 | M | NULL | NULL | | 29 | Song Jiang | 18 | M | 45 | NULL | | 36 | Song Jiang | 32 | M | 2 | 1 | +-------+-------------+-----+--------+---------+-----------+ 7 rows in set (0.00 sec) MariaDB [hellodb]> select * from students where name like '%s%'; +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 1 | Shi Zhongyu | 22 | M | 2 | 3 | | 2 | Shi Potian | 22 | M | 1 | 7 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 10 | Yue Lingshan | 19 | F | 3 | NULL | | 14 | Lu Wushuang | 17 | F | 3 | NULL | | 25 | Sun Dasheng | 100 | M | NULL | NULL | | 27 | sanhai | 35 | M | NULL | NULL | | 29 | Song Jiang | 18 | M | 45 | NULL | | 30 | Zhang Sanfeng | 18 | M | 94 | NULL | | 31 | Miejue Shitai | 18 | F | 77 | NULL | | 36 | Song Jiang | 32 | M | 2 | 1 | | 37 | Zhang Sanfeng | 94 | M | NULL | NULL | | 38 | Miejue Shitai | 77 | F | NULL | NULL | +-------+---------------+-----+--------+---------+-----------+ 13 rows in set (0.00 sec) ``` - _ 任意单个字符 ```sql MariaDB [hellodb]> select * from students where name like '_________'; +-------+-----------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+-----------+-----+--------+---------+-----------+ | 3 | Xie Yanke | 53 | M | 2 | 16 | | 4 | Ding Dian | 32 | M | 4 | 4 | | 5 | Yu Yutong | 26 | M | 3 | 1 | | 8 | Lin Daiyu | 17 | F | 7 | NULL | | 17 | Lin Chong | 25 | M | 4 | NULL | | 20 | Diao Chan | 19 | F | 7 | NULL | | 22 | Xiao Qiao | 20 | F | 1 | NULL | +-------+-----------+-----+--------+---------+-----------+ 7 rows in set (0.00 sec) MariaDB [hellodb]> select * from students where name like '________'; +-------+----------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+----------+-----+--------+---------+-----------+ | 6 | Shi Qing | 46 | M | 5 | NULL | | 18 | Hua Rong | 23 | M | 7 | NULL | +-------+----------+-----+--------+---------+-----------+ 2 rows in set (0.00 sec) ```
```sql MariaDB [hellodb]> select * from students where name rlike '^x'; +-------+-------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+-------------+-----+--------+---------+-----------+ | 3 | Xie Yanke | 53 | M | 2 | 16 | | 7 | Xi Ren | 19 | F | 3 | NULL | | 16 | Xu Zhu | 21 | M | 1 | NULL | | 19 | Xue Baochai | 18 | F | 6 | NULL | | 22 | Xiao Qiao | 20 | F | 1 | NULL | | 24 | Xu Xian | 27 | M | NULL | NULL | +-------+-------------+-----+--------+---------+-----------+ ```
``` MariaDB [hellodb]> select * from students where name regexp '^x'; +-------+-------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+-------------+-----+--------+---------+-----------+ | 3 | Xie Yanke | 53 | M | 2 | 16 | | 7 | Xi Ren | 19 | F | 3 | NULL | | 16 | Xu Zhu | 21 | M | 1 | NULL | | 19 | Xue Baochai | 18 | F | 6 | NULL | | 22 | Xiao Qiao | 20 | F | 1 | NULL | | 24 | Xu Xian | 27 | M | NULL | NULL | +-------+-------------+-----+--------+---------+-----------+ 6 rows in set (0.00 sec) ```
``` MariaDB [hellodb]> select * from students where AGE < 20 OR AGE >50; +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 3 | Xie Yanke | 53 | M | 2 | 16 | | 7 | Xi Ren | 19 | F | 3 | NULL | | 8 | Lin Daiyu | 17 | F | 7 | NULL | | 10 | Yue Lingshan | 19 | F | 3 | NULL | | 12 | Wen Qingqing | 19 | F | 1 | NULL | | 14 | Lu Wushuang | 17 | F | 3 | NULL | | 15 | Duan Yu | 19 | M | 4 | NULL | | 19 | Xue Baochai | 18 | F | 6 | NULL | | 20 | Diao Chan | 19 | F | 7 | NULL | | 25 | Sun Dasheng | 100 | M | NULL | NULL | | 29 | Song Jiang | 18 | M | 45 | NULL | | 30 | Zhang Sanfeng | 18 | M | 94 | NULL | | 31 | Miejue Shitai | 18 | F | 77 | NULL | | 32 | Lin Chaoying | 18 | F | 93 | NULL | | 37 | Zhang Sanfeng | 94 | M | NULL | NULL | | 38 | Miejue Shitai | 77 | F | NULL | NULL | | 39 | Lin Chaoying | 93 | F | NULL | NULL | +-------+---------------+-----+--------+---------+-----------+ 17 rows in set (0.00 sec) ```
-
GROUP:根据指定的条件把查询结果进行“分组”以用于做“聚合”运算
-
常见聚合函数:avg(), max(), min(), count(), sum()
-
HAVING: 对分组聚合运算后的结果指定过滤条件;写在分组后
-
where:对表过滤后在进行分组聚合运算;写在分租前
-
显示聚合函数和分组字段,其他字段没有意义
MariaDB [hellodb]> select count(stuid) from students; +--------------+ | count(stuid) | +--------------+ | 36 | +--------------+ 1 row in set (0.00 sec) MariaDB [hellodb]> select count(1) from students; +----------+ | count(1) | +----------+ | 36 | +----------+ 1 row in set (0.00 sec) MariaDB [hellodb]> select count(2) from students; +----------+ | count(2) | +----------+ | 36 | +----------+ 1 row in set (0.00 sec) MariaDB [hellodb]> select count(*) from students; +----------+ | count(*) | +----------+ | 36 | +----------+ 1 row in set (0.00 sec) MariaDB [hellodb]> select gender 性别,count(*)人数 from students group by gender; +--------+--------+ | 性别 | 人数 | +--------+--------+ | F | 15 | | M | 21 | +--------+--------+ 2 rows in set (0.00 sec) MariaDB [hellodb]> select name,gender,min(age) from students group by gender; +-------------+--------+----------+ | name | gender | min(age) | +-------------+--------+----------+ | Xi Ren | F | 17 | | Shi Zhongyu | M | 18 | +-------------+--------+----------+ 2 rows in set (0.00 sec) MariaDB [hellodb]> select name,gender,max(age) from students group by gender; +-------------+--------+----------+ | name | gender | max(age) | +-------------+--------+----------+ | Xi Ren | F | 93 | | Shi Zhongyu | M | 100 | +-------------+--------+----------+ MariaDB [hellodb]> select classid,gender,avg(age) from students group by classid,gender; \\先对班级分组,组队班级中的性别分组;计算每个班级中男女生的平均年纪。 +---------+--------+----------+ | classid | gender | avg(age) | +---------+--------+----------+ | NULL | F | 85.0000 | | NULL | M | 57.8000 | | 1 | F | 19.5000 | | 1 | M | 21.5000 | | 2 | F | 32.0000 | | 2 | M | 35.0000 | | 3 | F | 18.3333 | | 3 | M | 26.0000 | | 4 | M | 24.7500 | | 5 | M | 46.0000 | | 6 | F | 20.0000 | | 6 | M | 23.0000 | | 7 | F | 18.0000 | | 7 | M | 23.0000 | | 45 | M | 18.0000 | | 77 | F | 18.0000 | | 93 | F | 18.0000 | | 94 | M | 18.0000 | +---------+--------+----------+ 18 rows in set (0.00 sec) MariaDB [hellodb]> select classid,gender,avg(age) from students group by classid,gender having classid is not null; //先分组再过滤记录。 +---------+--------+----------+ | classid | gender | avg(age) | +---------+--------+----------+ | 1 | F | 19.5000 | | 1 | M | 21.5000 | | 2 | F | 32.0000 | | 2 | M | 35.0000 | | 3 | F | 18.3333 | | 3 | M | 26.0000 | | 4 | M | 24.7500 | | 5 | M | 46.0000 | | 6 | F | 20.0000 | | 6 | M | 23.0000 | | 7 | F | 18.0000 | | 7 | M | 23.0000 | | 45 | M | 18.0000 | | 77 | F | 18.0000 | | 93 | F | 18.0000 | | 94 | M | 18.0000 | +---------+--------+----------+ 16 rows in set (0.00 sec) MariaDB [hellodb]> select classid,gender,avg(age) from students where classid is not null group by classid,gender; //先过滤记录再做分租 +---------+--------+----------+ | classid | gender | avg(age) | +---------+--------+----------+ | 1 | F | 19.5000 | | 1 | M | 21.5000 | | 2 | F | 32.0000 | | 2 | M | 35.0000 | | 3 | F | 18.3333 | | 3 | M | 26.0000 | | 4 | M | 24.7500 | | 5 | M | 46.0000 | | 6 | F | 20.0000 | | 6 | M | 23.0000 | | 7 | F | 18.0000 | | 7 | M | 23.0000 | | 45 | M | 18.0000 | | 77 | F | 18.0000 | | 93 | F | 18.0000 |
-
| 94 | M | 18.0000 |
±--------±-------±---------+
16 rows in set (0.00 sec)
- ##### ORDER BY: 根据指定的字段对查询结果进行排序-->排序前要先过滤记录
- ###### 升序:ASC
- ###### 降序:DESC
```sql
MariaDB [hellodb]> select * from students where classid is not null order by classid asc; \\升序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
| 16 | Xu Zhu | 21 | M | 1 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 26 | nanchen | 32 | F | 2 | 1 |
| 36 | Song Jiang | 32 | M | 2 | 1 |
| 13 | Tian Boguang | 33 | M | 2 | NULL |
MariaDB [hellodb]> select * from students where classid is not null order by -classid asc; \\降序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 18 | Hua Rong | 23 | M | 7 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
MariaDB [hellodb]> select * from students where classid is not null order by classid desc; \\降序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 18 | Hua Rong | 23 | M | 7 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
| 21 | Huang Yueying | 22 | F | 6 | NULL |
| 19 | Xue Baochai | 18 | F | 6 | NULL |
MariaDB [hellodb]> select * from students where classid is not null order by -classid desc; \\升序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
| 16 | Xu Zhu | 21 | M | 1 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 26 | nanchen | 32 | F | 2 | 1 |
| 36 | Song Jiang | 32 | M | 2 | 1 |
MariaDB [hellodb]> select * from students where classid is not null order by gender desc,classid desc; \\先对性别降序排序,性别相同的再对班级降序排序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 18 | Hua Rong | 23 | M | 7 | NULL |
| 11 | Yuan Chengzhi | 23 | M | 6 | NULL |
| 6 | Shi Qing | 46 | M | 5 | NULL |
| 15 | Duan Yu | 19 | M | 4 | NULL |
| 17 | Lin Chong | 25 | M | 4 | NULL |
| 23 | Ma Chao | 23 | M | 4 | NULL |
| 4 | Ding Dian | 32 | M | 4 | 4 |
| 5 | Yu Yutong | 26 | M | 3 | 1 |
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 13 | Tian Boguang | 33 | M | 2 | NULL |
| 36 | Song Jiang | 32 | M | 2 | 1 |
| 3 | Xie Yanke | 53 | M | 2 | 16 |
| 16 | Xu Zhu | 21 | M | 1 | NULL |
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
| 21 | Huang Yueying | 22 | F | 6 | NULL |
| 19 | Xue Baochai | 18 | F | 6 | NULL |
| 9 | Ren Yingying | 20 | F | 6 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 10 | Yue Lingshan | 19 | F | 3 | NULL |
| 14 | Lu Wushuang | 17 | F | 3 | NULL |
| 26 | nanchen | 32 | F | 2 | 1 |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
+-------+---------------+-----+--------+---------+-----------+
29 rows in set (0.01 sec)
MariaDB [hellodb]> select * from students where classid is not null order by gender,classid ;\\先对性别排序,性别相同的再对班级排序
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
| 26 | nanchen | 32 | F | 2 | 1 |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 10 | Yue Lingshan | 19 | F | 3 | NULL |
| 14 | Lu Wushuang | 17 | F | 3 | NULL |
| 21 | Huang Yueying | 22 | F | 6 | NULL |
| 9 | Ren Yingying | 20 | F | 6 | NULL |
| 19 | Xue Baochai | 18 | F | 6 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 16 | Xu Zhu | 21 | M | 1 | NULL |
| 2 | Shi Potian | 22 | M | 1 | 7 |
| 1 | Shi Zhongyu | 22 | M | 2 | 3 |
| 3 | Xie Yanke | 53 | M | 2 | 16 |
| 36 | Song Jiang | 32 | M | 2 | 1 |
| 13 | Tian Boguang | 33 | M | 2 | NULL |
| 5 | Yu Yutong | 26 | M | 3 | 1 |
| 17 | Lin Chong | 25 | M | 4 | NULL |
| 4 | Ding Dian | 32 | M | 4 | 4 |
| 23 | Ma Chao | 23 | M | 4 | NULL |
| 15 | Duan Yu | 19 | M | 4 | NULL |
| 6 | Shi Qing | 46 | M | 5 | NULL |
| 11 | Yuan Chengzhi | 23 | M | 6 | NULL |
| 18 | Hua Rong | 23 | M | 7 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
+-------+---------------+-----+--------+---------+-----------+
29 rows in set (0.01 sec)
```
- ##### LIMIT [[offset,]row_count]:对查询的结果进行输出行数数量限制
```
MariaDB [hellodb]> select * from students where classid is not null order by age limit 10;对年纪排序再取前10个;
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 14 | Lu Wushuang | 17 | F | 3 | NULL |
| 8 | Lin Daiyu | 17 | F | 7 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 31 | Miejue Shitai | 18 | F | 77 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 19 | Xue Baochai | 18 | F | 6 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
+-------+---------------+-----+--------+---------+-----------+
10 rows in set (0.00 sec)
MariaDB [hellodb]> select * from students where classid is not null order by age limit 3,10;对年纪排序后跳过3个取10个。
+-------+---------------+-----+--------+---------+-----------+
| StuID | Name | Age | Gender | ClassID | TeacherID |
+-------+---------------+-----+--------+---------+-----------+
| 19 | Xue Baochai | 18 | F | 6 | NULL |
| 32 | Lin Chaoying | 18 | F | 93 | NULL |
| 29 | Song Jiang | 18 | M | 45 | NULL |
| 30 | Zhang Sanfeng | 18 | M | 94 | NULL |
| 20 | Diao Chan | 19 | F | 7 | NULL |
| 12 | Wen Qingqing | 19 | F | 1 | NULL |
| 10 | Yue Lingshan | 19 | F | 3 | NULL |
| 15 | Duan Yu | 19 | M | 4 | NULL |
| 7 | Xi Ren | 19 | F | 3 | NULL |
| 22 | Xiao Qiao | 20 | F | 1 | NULL |
+-------+---------------+-----+--------+---------+-----------+
10 rows in set (0.00 sec)
```
- ##### 对查询结果中的数据请求施加“锁”
FOR UPDATE: 写锁,独占或排它锁,只有一个读和写操作
LOCK IN SHARE MODE: 读锁,共享锁,同时多个读操作
###### 范例
```SQL
DESC students;
INSERT INTO students VALUES(1,'tom','m'),(2,'alice','f'); \\字符串要用''引用
INSERT INTO students(id,name) VALUES(3,'jack'),(4,'allen');
SELECT * FROM students WHERE id < 3;
SELECT * FROM students WHERE gender='m';
SELECT * FROM students WHERE gender IS NULL;
SELECT * FROM students WHERE gender IS NOT NULL;
SELECT * FROM students ORDER BY name DESC LIMIT 2;
SELECT * FROM students ORDER BY name DESC LIMIT 1,2;
SELECT * FROM students WHERE id >=2 and id <=4;
SELECT * FROM students WHERE BETWEEN 2 AND 4
SELECT * FROM students WHERE name LIKE ‘t%’
SELECT * FROM students WHERE name RLIKE '.*[lo].*';
SELECT id stuid,name as stuname FROM students
select * from students where classid in (1,3,5);
select classid,avg(age) as 平均年龄 from students where classid > 3 group by
classid having 平均年龄 >30 ;
MariaDB [hellodb]> select classid,avg(age) as 平均年龄 from students where classid > 3 group by classid;
+---------+--------------+
| classid | 平均年龄 |
+---------+--------------+
| 4 | 24.7500 |
| 5 | 46.0000 |
| 6 | 20.7500 |
| 7 | 19.6667 |
| 45 | 18.0000 |
| 77 | 18.0000 |
| 93 | 18.0000 |
| 94 | 18.0000 |
+---------+--------------+
8 rows in set (0.00 sec)
MariaDB [hellodb]> select classid,avg(age) as 平均年龄 from students where classid > 3 group by classid having 平均年龄 >30 ;
+---------+--------------+
| classid | 平均年龄 |
+---------+--------------+
| 5 | 46.0000 |
+---------+--------------+
1 row in set (0.00 sec)
*****************************************************************************************
#SQL 注入 :黑客冒充用户登录
MariaDB [hellodb]> select * from user;
+----+-------+----------+
| id | name | password |
+----+-------+----------+
| 1 | alice | yanyi |
| 2 | tom | tom |
+----+-------+----------+
2 rows in set (0.00 sec)
MariaDB [hellodb]> select * from user where name='tom' and password='tom'; \\正常查询
+----+------+----------+
| id | name | password |
+----+------+----------+
| 2 | tom | tom |
+----+------+----------+
1 row in set (0.00 sec)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
select * from user where name='admin' and password='' or '1'='1'; \\SQL注入录
MariaDB [hellodb]> select * from user where name='tom' and password='' or '1'='1';
+----+-------+----------+
| id | name | password |
+----+-------+----------+
| 1 | alice | yanyi |
| 2 | tom | tom |
+----+-------+----------+
2 rows in set (0.00 sec)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
select * from user where name='admin' and password='' or '1=1'; \\SQL注入录
MariaDB [hellodb]> select * from user where name='alice' and password='' or '1=1';
+----+-------+----------+
| id | name | password |
+----+-------+----------+
| 1 | alice | yanyi |
| 2 | tom | tom |
+----+-------+----------+
2 rows in set, 5 warnings (0.00 sec)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
select * from user where name='admin'; -- ' and password='magedu123'; \\SQL冒充用户登录
MariaDB [hellodb]> select * from user where name='tom'; -- ' and password='tom';
+----+------+----------+
| id | name | password |
+----+------+----------+
| 2 | tom | tom |
+----+------+----------+
1 row in set (0.00 sec)
*****************************************************************************************
select classid,sum(age) from students where classid is not null group by
classid order by classid;
select classid,sum(age) from students group by classid having classid is not
null order by classid;
MariaDB [hellodb]> select classid,sum(age) from students where classid is not null group by classid order by classid;
+---------+----------+
| classid | sum(age) |
+---------+----------+
| 1 | 82 |
| 2 | 172 |
| 3 | 81 |
| 4 | 99 |
| 5 | 46 |
| 6 | 83 |
| 7 | 59 |
| 45 | 18 |
| 77 | 18 |
| 93 | 18 |
| 94 | 18 |
+---------+----------+
11 rows in set (0.00 sec)
MariaDB [hellodb]> select classid,sum(age) from students group by classid having classid is not null order by classid;
+---------+----------+
| classid | sum(age) |
+---------+----------+
| 1 | 82 |
| 2 | 172 |
| 3 | 81 |
| 4 | 99 |
| 5 | 46 |
| 6 | 83 |
| 7 | 59 |
| 45 | 18 |
| 77 | 18 |
| 93 | 18 |
| 94 | 18 |
+---------+----------+
11 rows in set (0.00 sec)
*****************************************************************************************
select classid,sum(age) from students where classid is not null group by
classid order by classid limit 2,3;
MariaDB [hellodb]> select classid,sum(age) from students where classid is not null group by classid order by classid limit 2,3;
+---------+----------+
| classid | sum(age) |
+---------+----------+
| 3 | 81 |
| 4 | 99 |
| 5 | 46 |
+---------+----------+
3 rows in set (0.00 sec)
select gender,avg(age) 平均年龄 from students group by gender having gender='M';
select classid,gender,avg(age) from students group by classid,gender;
#对classid 正序排序,NULL记录排在最后
select *from students order by -classid desc ;
#多列排序
select * from students order by gender desc, age asc;
#必须先过滤,再排序
select * from students where classid is not null order by gender desc, age asc ;
#分组后再排序
MariaDB [hellodb]> select gender,classid,avg(age) from students where classid is not null group by gender,classid order by gender,classid;
+--------+---------+----------+
| gender | classid | avg(age) |
+--------+---------+----------+
| F | 1 | 19.5000 |
| F | 2 | 32.0000 |
| F | 3 | 18.3333 |
| F | 6 | 20.0000 |
| F | 7 | 18.0000 |
| F | 77 | 18.0000 |
| F | 93 | 18.0000 |
| M | 1 | 21.5000 |
| M | 2 | 35.0000 |
| M | 3 | 26.0000 |
| M | 4 | 24.7500 |
| M | 5 | 46.0000 |
| M | 6 | 23.0000 |
| M | 7 | 23.0000 |
| M | 45 | 18.0000 |
| M | 94 | 18.0000 |
+--------+---------+----------+
16 rows in set (0.00 sec)
MariaDB [hellodb]> select gender,classid,avg(age) from students where classid is not null group by classid,gender order by gender,classid;
+--------+---------+----------+
| gender | classid | avg(age) |
+--------+---------+----------+
| F | 1 | 19.5000 |
| F | 2 | 32.0000 |
| F | 3 | 18.3333 |
| F | 6 | 20.0000 |
| F | 7 | 18.0000 |
| F | 77 | 18.0000 |
| F | 93 | 18.0000 |
| M | 1 | 21.5000 |
| M | 2 | 35.0000 |
| M | 3 | 26.0000 |
| M | 4 | 24.7500 |
| M | 5 | 46.0000 |
| M | 6 | 23.0000 |
| M | 7 | 23.0000 |
| M | 45 | 18.0000 |
| M | 94 | 18.0000 |
+--------+---------+----------+
16 rows in set (0.00 sec)
*****************************************************************************************
MariaDB [hellodb]> select * from students order by age limit 10;
MariaDB [hellodb]> select * from students order by age limit 3,10;
MariaDB [hellodb]> select distinct age from students order by age limit 3; \\去重复排序取值
MariaDB [hellodb]> select distinct age from students order by age limit 3,5 ;
4.7.2 多表查询
查询结果来自于多张表,即多表查询
![image-20191121104558366](image-20191121104558366.png)
-
子查询:在SQL语句嵌套着查询语句,性能较差,基于某语句的查询结果再次进行的查询
MariaDB [hellodb]> select avg(age) from students; +----------+ | avg(age) | +----------+ | 32.0278 | +----------+ 1 row in set (0.01 sec) MariaDB[hellodb]> select * from students where age > (select avg(age) from students ); +-------+---------------+-----+--------+---------+-----------+ | StuID | Name | Age | Gender | ClassID | TeacherID | +-------+---------------+-----+--------+---------+-----------+ | 3 | Xie Yanke | 53 | M | 2 | 16 | | 6 | Shi Qing | 46 | M | 5 | NULL | | 13 | Tian Boguang | 33 | M | 2 | NULL | | 25 | Sun Dasheng | 100 | M | NULL | NULL | | 27 | sanhai | 35 | M | NULL | NULL | | 28 | meichaofeng | 33 | M | NULL | NULL | | 37 | Zhang Sanfeng | 94 | M | NULL | NULL | | 38 | Miejue Shitai | 77 | F | NULL | NULL | | 39 | Lin Chaoying | 93 | F | NULL | NULL | +-------+---------------+-----+--------+---------+-----------+ 9 rows in set (0.00 sec)
##在SQL语句嵌套着查询语句 MariaDB [hellodb]> select * from teachers; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 93 | F | +-----+---------------+-----+--------+ 4 rows in set (0.00 sec) MariaDB [hellodb]> update teachers set age=(select avg(age) from students) where tid=4; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 MariaDB [hellodb]> select * from teachers; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | +-----+---------------+-----+--------+ 4 rows in set (0.00 sec)
-
联合查询:UNION
MariaDB [hellodb]> select stuid,name,age,gender from students where stuid < 5 union select * from teachers; +-------+---------------+-----+--------+ | stuid | name | age | gender | +-------+---------------+-----+--------+ | 1 | Shi Zhongyu | 22 | M | | 2 | Shi Potian | 22 | M | | 3 | Xie Yanke | 53 | M | | 4 | Ding Dian | 32 | M | | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | +-------+---------------+-----+--------+ 8 rows in set (0.00 sec) MariaDB [hellodb]> select * from teachers union select stuid,name,age,gender from students where stuid < 5; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | | 1 | Shi Zhongyu | 22 | M | | 2 | Shi Potian | 22 | M | | 3 | Xie Yanke | 53 | M | | 4 | Ding Dian | 32 | M | +-----+---------------+-----+--------+ 8 rows in set (0.01 sec) ##同一个表做联合查询union,可以剔除相同的记录。 MariaDB [hellodb]> select * from teachers union select * from teachers; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | +-----+---------------+-----+--------+ 4 rows in set (0.00 sec) MariaDB [hellodb]> select * from t1; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 26 | F | | 4 | Lin Chaoying | 26 | F | +-----+---------------+-----+--------+ 5 rows in set (0.01 sec) MariaDB [hellodb]> select * from t1 union select * from t1 ; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 26 | F | +-----+---------------+-----+--------+ 4 rows in set (0.00 sec) MariaDB [hellodb]> select distinct * from t1; +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 26 | F | +-----+---------------+-----+--------+ 4 rows in set (0.00 sec) MariaDB [hellodb]> select * from t1 union all select * from t1 ; //all关键字不去重 +-----+---------------+-----+--------+ | TID | Name | Age | Gender | +-----+---------------+-----+--------+ | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | | 4 | Lin Chaoying | 26 | F | | 4 | Lin Chaoying | 32 | F | | 4 | Lin Chaoying | 26 | F | | 1 | Song Jiang | 45 | M | | 2 | Zhang Sanfeng | 94 | M | | 3 | Miejue Shitai | 77 | F | | 4 | Lin Chaoying | 32 | F | | 4 | Lin Chaoying | 26 | F | | 4 | Lin Chaoying | 32 | F | | 4 | Lin Chaoying | 26 | F | +-----+---------------+-----+--------+ 14 rows in set (0.00 sec)
-
交叉连接:笛卡尔乘积 (横向合并)cross join
MariaDB [hellodb]> select * from students cross join teachers;
MariaDB [hellodb]> select * from students,teachers;
MariaDB [hellodb]> select * from teachers cross join students;
MariaDB [hellodb]> select * from teachers,students;
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age, tid,t.name teacher_name,t.age teacher_age from students s cross join teachers t where stuid <4;
+-------+--------------+-------------+-----+---------------+-------------+
| stuid | student_name | student_age | tid | teacher_name | teacher_age |
+-------+--------------+-------------+-----+---------------+-------------+
| 1 | Shi Zhongyu | 22 | 1 | Song Jiang | 45 |
| 2 | Shi Potian | 22 | 1 | Song Jiang | 45 |
| 3 | Xie Yanke | 53 | 1 | Song Jiang | 45 |
| 1 | Shi Zhongyu | 22 | 2 | Zhang Sanfeng | 94 |
| 2 | Shi Potian | 22 | 2 | Zhang Sanfeng | 94 |
| 3 | Xie Yanke | 53 | 2 | Zhang Sanfeng | 94 |
| 1 | Shi Zhongyu | 22 | 3 | Miejue Shitai | 77 |
| 2 | Shi Potian | 22 | 3 | Miejue Shitai | 77 |
| 3 | Xie Yanke | 53 | 3 | Miejue Shitai | 77 |
| 1 | Shi Zhongyu | 22 | 4 | Lin Chaoying | 32 |
| 2 | Shi Potian | 22 | 4 | Lin Chaoying | 32 |
| 3 | Xie Yanke | 53 | 4 | Lin Chaoying | 32 |
+-------+--------------+-------------+-----+---------------+-------------+
12 rows in set (0.00 sec)
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age, tid,t.name teacher_name,t.age teacher_age from teachers t cross join students s where stuid <4;
+-------+--------------+-------------+-----+---------------+-------------+
| stuid | student_name | student_age | tid | teacher_name | teacher_age |
+-------+--------------+-------------+-----+---------------+-------------+
| 1 | Shi Zhongyu | 22 | 1 | Song Jiang | 45 |
| 2 | Shi Potian | 22 | 1 | Song Jiang | 45 |
| 3 | Xie Yanke | 53 | 1 | Song Jiang | 45 |
| 1 | Shi Zhongyu | 22 | 2 | Zhang Sanfeng | 94 |
| 2 | Shi Potian | 22 | 2 | Zhang Sanfeng | 94 |
| 3 | Xie Yanke | 53 | 2 | Zhang Sanfeng | 94 |
| 1 | Shi Zhongyu | 22 | 3 | Miejue Shitai | 77 |
| 2 | Shi Potian | 22 | 3 | Miejue Shitai | 77 |
| 3 | Xie Yanke | 53 | 3 | Miejue Shitai | 77 |
| 1 | Shi Zhongyu | 22 | 4 | Lin Chaoying | 32 |
| 2 | Shi Potian | 22 | 4 | Lin Chaoying | 32 |
| 3 | Xie Yanke | 53 | 4 | Lin Chaoying | 32 |
+-------+--------------+-------------+-----+---------------+-------------+
12 rows in set (0.00 sec)
##一旦定义了别名,就必须使用别名,不能使用原始名。
-
内连接:
-
等值连接:让表之间的字段以“等值”建立连接关系 inner join on
##cross join where ariaDB [hellodb]> select stuid,s.name student_name,teacherid,tid,t.name teacher_name from teachers t cross join students s where s.TeacherID =t.tid; +-------+--------------+-----------+-----+---------------+ | stuid | student_name | teacherid | tid | teacher_name | +-------+--------------+-----------+-----+---------------+ | 5 | Yu Yutong | 1 | 1 | Song Jiang | | 1 | Shi Zhongyu | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 4 | 4 | Lin Chaoying | +-------+--------------+-----------+-----+---------------+ 3 rows in set (0.00 sec) ##inner join on MariaDB [hellodb]> select stuid,s.name student_name,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID =t.tid; +-------+--------------+-----------+-----+---------------+ | stuid | student_name | teacherid | tid | teacher_name | +-------+--------------+-----------+-----+---------------+ | 5 | Yu Yutong | 1 | 1 | Song Jiang | | 1 | Shi Zhongyu | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 4 | 4 | Lin Chaoying | +-------+--------------+-----------+-----+---------------+ 3 rows in set (0.00 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t cross join students s where s.teacherid is not null; +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 2 | Zhang Sanfeng | | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 1 | Shi Zhongyu | 22 | 3 | 4 | Lin Chaoying | | 2 | Shi Potian | 22 | 7 | 1 | Song Jiang | | 2 | Shi Potian | 22 | 7 | 2 | Zhang Sanfeng | | 2 | Shi Potian | 22 | 7 | 3 | Miejue Shitai | | 2 | Shi Potian | 22 | 7 | 4 | Lin Chaoying | | 3 | Xie Yanke | 53 | 16 | 1 | Song Jiang | | 3 | Xie Yanke | 53 | 16 | 2 | Zhang Sanfeng | | 3 | Xie Yanke | 53 | 16 | 3 | Miejue Shitai | | 3 | Xie Yanke | 53 | 16 | 4 | Lin Chaoying | | 4 | Ding Dian | 32 | 4 | 1 | Song Jiang | | 4 | Ding Dian | 32 | 4 | 2 | Zhang Sanfeng | | 4 | Ding Dian | 32 | 4 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 5 | Yu Yutong | 26 | 1 | 2 | Zhang Sanfeng | | 5 | Yu Yutong | 26 | 1 | 3 | Miejue Shitai | | 5 | Yu Yutong | 26 | 1 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 20 rows in set (0.00 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID <> t.tid; //不等值 +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 2 | Zhang Sanfeng | | 1 | Shi Zhongyu | 22 | 3 | 4 | Lin Chaoying | | 2 | Shi Potian | 22 | 7 | 1 | Song Jiang | | 2 | Shi Potian | 22 | 7 | 2 | Zhang Sanfeng | | 2 | Shi Potian | 22 | 7 | 3 | Miejue Shitai | | 2 | Shi Potian | 22 | 7 | 4 | Lin Chaoying | | 3 | Xie Yanke | 53 | 16 | 1 | Song Jiang | | 3 | Xie Yanke | 53 | 16 | 2 | Zhang Sanfeng | | 3 | Xie Yanke | 53 | 16 | 3 | Miejue Shitai | | 3 | Xie Yanke | 53 | 16 | 4 | Lin Chaoying | | 4 | Ding Dian | 32 | 4 | 1 | Song Jiang | | 4 | Ding Dian | 32 | 4 | 2 | Zhang Sanfeng | | 4 | Ding Dian | 32 | 4 | 3 | Miejue Shitai | | 5 | Yu Yutong | 26 | 1 | 2 | Zhang Sanfeng | | 5 | Yu Yutong | 26 | 1 | 3 | Miejue Shitai | | 5 | Yu Yutong | 26 | 1 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 17 rows in set (0.00 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID = t.tid; //等值 +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 3 rows in set (0.00 sec)
-
不等值连接
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID <> t.tid; //不等值 +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 2 | Zhang Sanfeng | | 1 | Shi Zhongyu | 22 | 3 | 4 | Lin Chaoying | | 2 | Shi Potian | 22 | 7 | 1 | Song Jiang | | 2 | Shi Potian | 22 | 7 | 2 | Zhang Sanfeng | | 2 | Shi Potian | 22 | 7 | 3 | Miejue Shitai | | 2 | Shi Potian | 22 | 7 | 4 | Lin Chaoying | | 3 | Xie Yanke | 53 | 16 | 1 | Song Jiang | | 3 | Xie Yanke | 53 | 16 | 2 | Zhang Sanfeng | | 3 | Xie Yanke | 53 | 16 | 3 | Miejue Shitai | | 3 | Xie Yanke | 53 | 16 | 4 | Lin Chaoying | | 4 | Ding Dian | 32 | 4 | 1 | Song Jiang | | 4 | Ding Dian | 32 | 4 | 2 | Zhang Sanfeng | | 4 | Ding Dian | 32 | 4 | 3 | Miejue Shitai | | 5 | Yu Yutong | 26 | 1 | 2 | Zhang Sanfeng | | 5 | Yu Yutong | 26 | 1 | 3 | Miejue Shitai | | 5 | Yu Yutong | 26 | 1 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 17 rows in set (0.00 sec)
-
自然连接:去掉重复列的等值连接
-
-
外连接:
-
左外连接:FROM tb1 LEFT JOIN tb2 ON tb1.col=tb2.col
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID = t.tid; //等值=students与teachers交集 +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 3 rows in set (0.00 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from students s left join teachers t on s.TeacherID = t.tid; //保留所有的students记录,students没有值的字段用NULL填充,且保留teachers与students的交集;tid=2的记录在students表中没记录,所以查询后就没有此记录;其他三条都有;tb1.col=tb2.col为了是查询交集的字段。 +-------+---------------+-------------+-----------+------+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+---------------+-------------+-----------+------+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 2 | Shi Potian | 22 | 7 | NULL | NULL | | 3 | Xie Yanke | 53 | 16 | NULL | NULL | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 6 | Shi Qing | 46 | NULL | NULL | NULL | | 7 | Xi Ren | 19 | NULL | NULL | NULL | | 8 | Lin Daiyu | 17 | NULL | NULL | NULL | | 9 | Ren Yingying | 20 | NULL | NULL | NULL | | 10 | Yue Lingshan | 19 | NULL | NULL | NULL | | 11 | Yuan Chengzhi | 23 | NULL | NULL | NULL | | 12 | Wen Qingqing | 19 | NULL | NULL | NULL | | 13 | Tian Boguang | 33 | NULL | NULL | NULL | | 14 | Lu Wushuang | 17 | NULL | NULL | NULL | | 15 | Duan Yu | 19 | NULL | NULL | NULL | | 16 | Xu Zhu | 21 | NULL | NULL | NULL | | 17 | Lin Chong | 25 | NULL | NULL | NULL | | 18 | Hua Rong | 23 | NULL | NULL | NULL | | 19 | Xue Baochai | 18 | NULL | NULL | NULL | | 20 | Diao Chan | 19 | NULL | NULL | NULL | | 21 | Huang Yueying | 22 | NULL | NULL | NULL | | 22 | Xiao Qiao | 20 | NULL | NULL | NULL | | 23 | Ma Chao | 23 | NULL | NULL | NULL | | 24 | Xu Xian | 27 | NULL | NULL | NULL | | 25 | Sun Dasheng | 100 | NULL | NULL | NULL | +-------+---------------+-------------+-----------+------+---------------+ 25 rows in set (0.01 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t right outer join students s on s.TeacherID = t.tid; +-------+---------------+-------------+-----------+------+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+---------------+-------------+-----------+------+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 2 | Shi Potian | 22 | 7 | NULL | NULL | | 3 | Xie Yanke | 53 | 16 | NULL | NULL | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 6 | Shi Qing | 46 | NULL | NULL | NULL | | 7 | Xi Ren | 19 | NULL | NULL | NULL | | 8 | Lin Daiyu | 17 | NULL | NULL | NULL | | 9 | Ren Yingying | 20 | NULL | NULL | NULL | | 10 | Yue Lingshan | 19 | NULL | NULL | NULL | | 11 | Yuan Chengzhi | 23 | NULL | NULL | NULL | | 12 | Wen Qingqing | 19 | NULL | NULL | NULL | | 13 | Tian Boguang | 33 | NULL | NULL | NULL | | 14 | Lu Wushuang | 17 | NULL | NULL | NULL | | 15 | Duan Yu | 19 | NULL | NULL | NULL | | 16 | Xu Zhu | 21 | NULL | NULL | NULL | | 17 | Lin Chong | 25 | NULL | NULL | NULL | | 18 | Hua Rong | 23 | NULL | NULL | NULL | | 19 | Xue Baochai | 18 | NULL | NULL | NULL | | 20 | Diao Chan | 19 | NULL | NULL | NULL | | 21 | Huang Yueying | 22 | NULL | NULL | NULL | | 22 | Xiao Qiao | 20 | NULL | NULL | NULL | | 23 | Ma Chao | 23 | NULL | NULL | NULL | | 24 | Xu Xian | 27 | NULL | NULL | NULL | | 25 | Sun Dasheng | 100 | NULL | NULL | NULL | +-------+---------------+-------------+-----------+------+---------------+ 25 rows in set (0.00 sec)
-
左外连接拓展用法
```sql MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from students s left outer join teachers t on s.TeacherID = t.tid where tid is null; // 去除左外连接的交集; +-------+---------------+-------------+-----------+------+--------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+---------------+-------------+-----------+------+--------------+ | 2 | Shi Potian | 22 | 7 | NULL | NULL | | 3 | Xie Yanke | 53 | 16 | NULL | NULL | | 6 | Shi Qing | 46 | NULL | NULL | NULL | | 7 | Xi Ren | 19 | NULL | NULL | NULL | | 8 | Lin Daiyu | 17 | NULL | NULL | NULL | | 9 | Ren Yingying | 20 | NULL | NULL | NULL | | 10 | Yue Lingshan | 19 | NULL | NULL | NULL | | 11 | Yuan Chengzhi | 23 | NULL | NULL | NULL | | 12 | Wen Qingqing | 19 | NULL | NULL | NULL | | 13 | Tian Boguang | 33 | NULL | NULL | NULL | | 14 | Lu Wushuang | 17 | NULL | NULL | NULL | | 15 | Duan Yu | 19 | NULL | NULL | NULL | | 16 | Xu Zhu | 21 | NULL | NULL | NULL | | 17 | Lin Chong | 25 | NULL | NULL | NULL | | 18 | Hua Rong | 23 | NULL | NULL | NULL | | 19 | Xue Baochai | 18 | NULL | NULL | NULL | | 20 | Diao Chan | 19 | NULL | NULL | NULL | | 21 | Huang Yueying | 22 | NULL | NULL | NULL | | 22 | Xiao Qiao | 20 | NULL | NULL | NULL | | 23 | Ma Chao | 23 | NULL | NULL | NULL | | 24 | Xu Xian | 27 | NULL | NULL | NULL | | 25 | Sun Dasheng | 100 | NULL | NULL | NULL | +-------+---------------+-------------+-----------+------+--------------+ 22 rows in set (0.00 sec) ```
-
右外连接:FROM tb1 RIGHT JOIN tb2 ON tb1.col=tb2.col
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from students s right outer join teachers t on s.TeacherID = t.tid; +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | NULL | NULL | NULL | NULL | 2 | Zhang Sanfeng | +-------+--------------+-------------+-----------+-----+---------------+ 4 rows in set (0.00 sec) //teachers表取全部值,students取交集的记录。 MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t inner join students s on s.TeacherID = t.tid; //等值=students与teachers交集;tb1.col=tb2.col为了是查询交集的字段。 +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | +-------+--------------+-------------+-----------+-----+---------------+ 3 rows in set (0.00 sec) MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from teachers t left outer join students s on s.TeacherID = t.tid; +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | 1 | Shi Zhongyu | 22 | 3 | 3 | Miejue Shitai | | 4 | Ding Dian | 32 | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 26 | 1 | 1 | Song Jiang | | NULL | NULL | NULL | NULL | 2 | Zhang Sanfeng | +-------+--------------+-------------+-----------+-----+---------------+ 4 rows in set (0.00 sec)
-
###### 右外连接拓展用法
MariaDB [hellodb]> select stuid,s.name student_name,s.age student_age,s.teacherid,tid,t.name teacher_name from students s right outer join teachers t on s.TeacherID = t.tid where teacherid is null;// 去除右外连接的交集; +-------+--------------+-------------+-----------+-----+---------------+ | stuid | student_name | student_age | teacherid | tid | teacher_name | +-------+--------------+-------------+-----------+-----+---------------+ | NULL | NULL | NULL | NULL | 2 | Zhang Sanfeng | +-------+--------------+-------------+-----------+-----+---------------+ 1 row in set (0.00 sec)
-
完全外连接
```sql MariaDB [hellodb]> select stuid,s.name student_name,s.teacherid,tid,t.name teacher_name from students s left join teachers t on TeacherID=tid union select stuid,s.name student_name,s.teacherid,tid,t.name teacher_name from students s right join teachers t on TeacherID=tid; //完全外连接:左外连接和右外连接取全集;union。 +-------+---------------+-----------+------+---------------+ | stuid | student_name | teacherid | tid | teacher_name | +-------+---------------+-----------+------+---------------+ | 1 | Shi Zhongyu | 3 | 3 | Miejue Shitai | | 2 | Shi Potian | 7 | NULL | NULL | | 3 | Xie Yanke | 16 | NULL | NULL | | 4 | Ding Dian | 4 | 4 | Lin Chaoying | | 5 | Yu Yutong | 1 | 1 | Song Jiang | | 6 | Shi Qing | NULL | NULL | NULL | | 7 | Xi Ren | NULL | NULL | NULL | | 8 | Lin Daiyu | NULL | NULL | NULL | | 9 | Ren Yingying | NULL | NULL | NULL | | 10 | Yue Lingshan | NULL | NULL | NULL | | 11 | Yuan Chengzhi | NULL | NULL | NULL | | 12 | Wen Qingqing | NULL | NULL | NULL | | 13 | Tian Boguang | NULL | NULL | NULL | | 14 | Lu Wushuang | NULL | NULL | NULL | | 15 | Duan Yu | NULL | NULL | NULL | | 16 | Xu Zhu | NULL | NULL | NULL | | 17 | Lin Chong | NULL | NULL | NULL | | 18 | Hua Rong | NULL | NULL | NULL | | 19 | Xue Baochai | NULL | NULL | NULL | | 20 | Diao Chan | NULL | NULL | NULL | | 21 | Huang Yueying | NULL | NULL | NULL | | 22 | Xiao Qiao | NULL | NULL | NULL | | 23 | Ma Chao | NULL | NULL | NULL | | 24 | Xu Xian | NULL | NULL | NULL | | 25 | Sun Dasheng | NULL | NULL | NULL | | NULL | NULL | NULL | 2 | Zhang Sanfeng | +-------+---------------+-----------+------+---------------+ 26 rows in set (0.00 sec) ##完全外连接扩展用法 MariaDB [hellodb]> select * from (select stuid,s.name student_name,s.teacherid,tid,t.name teacher_name from students s left join teachers t on TeacherID=tid union select stuid,s.name student_name,s.teacherid,tid,t.name teacher_name from students s right join teachers t on TeacherID=tid) as a where Teacherid is null or tid is null; //将完全外连接作为新的表做子查询(必须有别名);保留tid为null或者teacherid为null的记录。完全外连接(全集)删除等值内连接(交集)。 +-------+---------------+-----------+------+---------------+ | stuid | student_name | teacherid | tid | teacher_name | +-------+---------------+-----------+------+---------------+ | 2 | Shi Potian | 7 | NULL | NULL | | 3 | Xie Yanke | 16 | NULL | NULL | | 6 | Shi Qing | NULL | NULL | NULL | | 7 | Xi Ren | NULL | NULL | NULL | | 8 | Lin Daiyu | NULL | NULL | NULL | | 9 | Ren Yingying | NULL | NULL | NULL | | 10 | Yue Lingshan | NULL | NULL | NULL | | 11 | Yuan Chengzhi | NULL | NULL | NULL | | 12 | Wen Qingqing | NULL | NULL | NULL | | 13 | Tian Boguang | NULL | NULL | NULL | | 14 | Lu Wushuang | NULL | NULL | NULL | | 15 | Duan Yu | NULL | NULL | NULL | | 16 | Xu Zhu | NULL | NULL | NULL | | 17 | Lin Chong | NULL | NULL | NULL | | 18 | Hua Rong | NULL | NULL | NULL | | 19 | Xue Baochai | NULL | NULL | NULL | | 20 | Diao Chan | NULL | NULL | NULL | | 21 | Huang Yueying | NULL | NULL | NULL | | 22 | Xiao Qiao | NULL | NULL | NULL | | 23 | Ma Chao | NULL | NULL | NULL | | 24 | Xu Xian | NULL | NULL | NULL | | 25 | Sun Dasheng | NULL | NULL | NULL | | NULL | NULL | NULL | 2 | Zhang Sanfeng | +-------+---------------+-----------+------+---------------+ 23 rows in set (0.00 sec) ```
-
-
自连接:本表和本表进行连接查询
子查询
常用在WHERE子句中的子查询
- 用于比较表达式中的子查询;子查询仅能返回单个值
SELECT Name,Age FROM students WHERE Age>(SELECT avg(Age) FROM students);
- 用于IN中的子查询:子查询应该单键查询并返回一个或多个值构成列表
SELECT Name,Age FROM students WHERE Age IN (SELECT Age FROM teachers);
-
用于EXISTS
-
用于FROM子句中的子查询
使用格式:
SELECT tb_alias.col1,... FROM (SELECT clause) AS tb_alias WHERE Clause;
范例:
SELECT s.aage,s.ClassID FROM (SELECT avg(Age) AS aage,ClassID FROM students
WHERE ClassID IS NOT NULL GROUP BY ClassID) AS s WHERE s.aage>30;
联合查询:UNION
SELECT Name,Age FROM students UNION SELECT Name,Age FROM teachers;
4.7.3 SELECT语句处理的顺序
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HZtsH5Qz-1576071499579)(image-20191121105319739.png)]
-
查询执行路径中的组件:查询缓存、解析器、预处理器、优化器、查询执行引擎、存储引擎
-
SELECT语句的执行流程:
FROM Clause --> WHERE Clause --> GROUP BY --> HAVING Clause -->SELECT --> ORDER BY --> LIMIT
4.7.4 练习
导入hellodb.sql生成数据库
1. 在students表中,查询年龄大于25岁,且为男性的同学的名字和年龄
2. 以ClassID为分组依据,显示每组的平均年龄
3. 显示第2题中平均年龄大于30的分组及平均年龄
4. 显示以L开头的名字的同学的信息
5. 显示TeacherID非空的同学的相关信息
6. 以年龄排序后,显示年龄最大的前10位同学的信息
7. 查询年龄大于等于20岁,小于等于25岁的同学的信息
8. 以ClassID分组,显示每班的同学的人数
9. 以Gender分组,显示其年龄之和
10. 以ClassID分组,显示其平均年龄大于25的班级
11. 以Gender分组,显示各组中年龄大于25的学员的年龄之和
12. 显示前5位同学的姓名、课程及成绩
13. 显示其成绩高于80的同学的名称及课程
14. 取每位同学各门课的平均成绩,显示成绩前三名的同学的姓名和平均成绩
15. 显示每门课程课程名称及学习了这门课的同学的个数
16. 显示其年龄大于平均年龄的同学的名字
17. 显示其学习的课程为第1、2,4或第7门课的同学的名字
18. 显示其成员数最少为3个的班级的同学中年龄大于同班同学平均年龄的同学
19. 统计各班级中年龄大于全校同学平均年龄的同学
4.8 VIEW 视图
视图:虚拟表,保存有实表的查询结果
创建方法:
CREATE VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
查看视图定义:
SHOW CREATE VIEW view_name #只能看视图定义
SHOW CREATE TABLE view_name # 可以查看表和视图
删除视图:
DROP VIEW [IF EXISTS]
view_name [, view_name] ...
[RESTRICT | CASCADE]
注意:视图中的数据事实上存储于“基表”中,因此,其修改操作也会针对基表实现;其修改操作受基表限制
4.9 FUNCTION 函数
函数:分为系统函数和自定义函数
系统函数参考:
https://dev.mysql.com/doc/refman/5.7/en/func-op-summary-ref.html
自定义函数:user-defined function UDF,保存在mysql.proc表中
创建UDF语法
CREATE [AGGREGATE] FUNCTION function_name(parameter_name type,[parameter_name
type,...])
RETURNS {STRING|INTEGER|REAL}
runtime_body
说明:
参数可以有多个,也可以没有参数
必须有且只有一个返回值
查看函数列表:
SHOW FUNCTION STATUS;
查看函数定义
SHOW CREATE FUNCTION function_name
删除UDF:
DROP FUNCTION function_name
调用自定义函数语法:
SELECT function_name(parameter_value,...)
范例:
#无参UDF
CREATE FUNCTION simpleFun() RETURNS VARCHAR(20) RETURN "Hello World";
#有参数UDF
DELIMITER //
CREATE FUNCTION deleteById(id SMALLINT UNSIGNED) RETURNS VARCHAR(20)
BEGIN
DELETE FROM students WHERE stuid = id;
RETURN (SELECT COUNT(*) FROM students);
END//
DELIMITER ;
自定义函数中定义局部变量语法
DECLARE 变量1[,变量2,... ]变量类型 [DEFAULT 默认值]
- 说明:局部变量的作用范围是在BEGIN…END程序中,而且定义局部变量语句必须在BEGIN…END的第一行定义
范例:
DELIMITER //
CREATE FUNCTION addTwoNumber(x SMALLINT UNSIGNED, y SMALLINT UNSIGNED)
RETURNS SMALLINT
BEGIN
DECLARE a, b SMALLINT UNSIGNED;
SET a = x, b = y;
RETURN a+b;
END//
DELIMITER ;
为变量赋值语法
SET parameter_name = value[,parameter_name = value...]
SELECT INTO parameter_name
范例:
DECLARE x int;
SELECT COUNT(*) FROM tdb_name INTO x;
RETURN x;
END//
4.10 PROCEDURE 存储过程
存储过程:多表SQL的语句的集合,可以独立执行,存储过程保存在mysql.proc表中
存储过程优势:
- 存储过程把经常使用的SQL语句或业务逻辑封装起来,预编译保存在数据库中,当需要时从数据库中直接调用,省去了编译的过程
- 提高了运行速度
- 同时降低网络数据传输量
- 存储过程与自定义函数的区别
- 存储过程实现的过程要复杂一些,而函数的针对性较强
- 存储过程可以有多个返回值,而自定义函数只有一个返回值
- 存储过程一般可独立执行,而函数往往是作为其他SQL语句的一部分来使用
创建存储过程
CREATE PROCEDURE sp_name ([ proc_parameter [,proc_parameter ...]])
routime_body
proc_parameter : [IN|OUT|INOUT] parameter_name type
- 说明:其中IN表示输入参数,OUT表示输出参数,INOUT表示既可以输入也可以输出;param_name 表示参数名称;type表示参数的类型
查看存储过程列表
SHOW PROCEDURE STATUS;
查看存储过程定义
SHOW CREATE PROCEDURE sp_name
调用存储过程
CALL sp_name ([ proc_parameter [,proc_parameter ...]])
- 说明:当无参时,可以省略"()",当有参数时,不可省略"()”
存储过程修改
- ALTER语句修改存储过程只能修改存储过程的注释等无关紧要的东西,不能修改存储过程体,所以要修改存储过程,方法就是删除重建
删除存储过程
DROP PROCEDURE [IF EXISTS] sp_name
范例
# 创建无参存储过程
delimiter //
CREATE PROCEDURE showTime()
BEGIN
SELECT now();
END//
delimiter ;
CALL showTime;
范例
#创建含参存储过程:只有一个IN参数
delimiter //
CREATE PROCEDURE selectById(IN id SMALLINT UNSIGNED)
BEGIN
SELECT * FROM students WHERE stuid = id;
END//
delimiter ;
call selectById(2);
范例
delimiter //
CREATE PROCEDURE dorepeat(n INT)
BEGIN
SET @i = 0;
SET @sum = 0;
REPEAT SET @sum = @sum+@i;
SET @i = @i + 1;
UNTIL @i > n END REPEAT;
END//
delimiter ;
CALL dorepeat(100);
SELECT @sum;
范例
#创建含参存储过程:包含IN参数和OUT参数
delimiter //
CREATE PROCEDURE deleteById(IN id SMALLINT UNSIGNED, OUT num SMALLINT UNSIGNED)
BEGIN
DELETE FROM students WHERE stuid >= id;
SELECT row_count() into num;
END//
delimiter ;
call deleteById(2,@Line);
SELECT @Line;
#说明:创建存储过程deleteById,包含一个IN参数和一个OUT参数.调用时,传入删除的ID和保存被修改的行数值的用户变量@Line,select @Line;输出被影响行数
流程控制
存储过程和函数中可以使用流程控制来控制语句的执行
- IF:用来进行条件判断。根据是否满足条件,执行不同语句
- CASE:用来进行条件判断,可实现比IF语句更复杂的条件判断
- LOOP:重复执行特定的语句,实现一个简单的循环
- LEAVE:用于跳出循环控制
- ITERATE:跳出本次循环,然后直接进入下一次循环
- REPEAT:有条件控制的循环语句。当满足特定条件时,就会跳出循环语句
- WHILE:有条件控制的循环语句
4.11 TRIGGER触发器
触发器的执行不是由程序调用,也不是由手工启动,而是由事件来触发、激活从而实现执行
创建触发器
CREATE [DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
trigger_body
说明:
- trigger_name:触发器的名称
- trigger_time:{ BEFORE | AFTER },表示在事件之前或之后触发
- trigger_event::{ INSERT |UPDATE | DELETE },触发的具体事件
- tbl_name:该触发器作用在表名
范例:
#创建触发器,在向学生表INSERT数据时,学生数增加,DELETE学生时,学生数减少
CREATE TABLE student_info (
stu_id INT(11) NOT NULL AUTO_INCREMENT ,
stu_name VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (stu_id)
);
CREATE TABLE student_count (
student_count INT(11) DEFAULT 0
);
INSERT INTO student_count VALUES(0);
CREATE TRIGGER trigger_student_count_insert
AFTER INSERT
ON student_info FOR EACH ROW
UPDATE student_count SET student_count=student_count+1;
CREATE TRIGGER trigger_student_count_delete
AFTER DELETE
ON student_info FOR EACH ROW
UPDATE student_count SET student_count=student_count-1;
查看触发器
SHOW TRIGGERS
#查询系统表information_schema.triggers的方式指定查询条件,查看指定的触发器信息。
USE information_schema;
SELECT * FROM triggers WHERE trigger_name='trigger_student_count_insert';
删除触发器
DROP TRIGGER trigger_name;
4.12 MySQL用户管理
-
元数据数据库:mysql
-
系统授权表:
-
用户账号:
‘USERNAME’@‘HOST’
@‘HOST’:
主机名
IP地址或Network
通配符: % _
示例:172.16.%.%
-
创建用户:CREATE USER
CREATE USER 'USERNAME'@'HOST' [IDENTIFIED BY 'password'];
新建用户的默认权限:USAGE
-
用户重命名:RENAME USER
RENAME USER old_user_name TO new_user_name;
-
删除用户
DROP USER 'USERNAME'@'HOST‘
范例:删除默认的空用户
DROP USER ''@'localhost';
-
修改账户密码
#方法1 SET PASSWORD FOR 'user'@'host' = PASSWORD(‘password'); #方法2 UPDATE mysql.user SET password=PASSWORD('password') WHERE clause; #mariadb 10.3 update mysql.user set authentication_string=password('ubuntu') where user='mage'; #此方法需要执行下面指令才能生效: FLUSH PRIVILEGES;
-
忘记管理员密码的解决办法:
1. 启动mysqld进程时,为其使用如下选项: --skip-grant-tables --skip-networking 2. 使用UPDATE命令修改管理员密码 3. 关闭mysqld进程,移除上述两个选项,重启mysqld
-
范例:
[root@centos8 ~]#vim /etc/my.cnf [mysqld] skip-grant-tables skip-networking [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#mysql #mariadb 新版 MariaDB [(none)]> update mysql.user set authentication_string=password('ubuntu') where user='root'; ##mariadb 旧版 MariaDB [(none)]> update mysql.user set password=password('ubuntu') where user='root'; [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#vim /etc/my.cnf [mysqld] #skip-grant-tables #skip-networking [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#mysql -uroot -pubuntu
-
4.13 权限管理和DCL语句
权限类别:
管理类:
CREATE TEMPORARY TABLES
CREATE USER
FILE
SUPER
SHOW DATABASES
RELOAD
SHUTDOWN
REPLICATION SLAVE
REPLICATION CLIENT
LOCK TABLES
PROCESS
程序类:针对 FUNCTION、PROCEDURE、TRIGGER
CREATE
ALTER
DROP
EXCUTE
库和表级别:针对 DATABASE、TABLE
ALTER
CREATE
CREATE VIEW
DROP INDEX
SHOW VIEW
GRANT OPTION:能将自己获得的权限转赠给其他用户
数据操作
SELECT
INSERT
DELETE
UPDATE
字段级别
SELECT(col1,col2,...)
UPDATE(col1,col2,...)
INSERT(col1,col2,...)
所有权限
ALL PRIVILEGES 或 ALL
授权:GRANT
GRANT priv_type [(column_list)],... ON [object_type] priv_level TO 'user'@'host'
[IDENTIFIED BY 'password'] [WITH GRANT OPTION];
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 count
| MAX_UPDATES_PER_HOUR count
| MAX_CONNECTIONS_PER_HOUR count
| MAX_USER_CONNECTIONS count
参考:https://dev.mysql.com/doc/refman/5.7/en/grant.html
范例:
GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO 'someuser'@'somehost‘;
GRANT ALL ON wordpress.* TO wordpress@'192.168.39.%' IDENTIFIED BY 'magedu';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.39.%' IDENTIFIED BY 'magedu'
WITH GRANT OPTION;
取消授权:REVOKE
REVOKE priv_type [(column_list)] [, priv_type [(column_list)]] ... ON
[object_type] priv_level FROM user [, user] ...
参考:https://dev.mysql.com/doc/refman/5.7/en/revoke.html
范例:
REVOKE DELETE ON testdb.* FROM 'testuser'@‘172.16.0.%’;
查看指定用户获得的授权
Help SHOW GRANTS
SHOW GRANTS FOR 'user'@'host';
SHOW GRANTS FOR CURRENT_USER[()];
注意:MariaDB服务进程启动时会读取mysql库中所有授权表至内存
(1) GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效
d’) WHERE clause;
#mariadb 10.3
update mysql.user set authentication_string=password(‘ubuntu’) where
user=‘mage’;
#此方法需要执行下面指令才能生效:
FLUSH PRIVILEGES;
```
-
忘记管理员密码的解决办法:
1. 启动mysqld进程时,为其使用如下选项: --skip-grant-tables --skip-networking 2. 使用UPDATE命令修改管理员密码 3. 关闭mysqld进程,移除上述两个选项,重启mysqld
-
范例:
[root@centos8 ~]#vim /etc/my.cnf [mysqld] skip-grant-tables skip-networking [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#mysql #mariadb 新版 MariaDB [(none)]> update mysql.user set authentication_string=password('ubuntu') where user='root'; ##mariadb 旧版 MariaDB [(none)]> update mysql.user set password=password('ubuntu') where user='root'; [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#vim /etc/my.cnf [mysqld] #skip-grant-tables #skip-networking [root@centos8 ~]#systemctl restart mariadb [root@centos8 ~]#mysql -uroot -pubuntu
-
4.13 权限管理和DCL语句
权限类别:
管理类:
CREATE TEMPORARY TABLES
CREATE USER
FILE
SUPER
SHOW DATABASES
RELOAD
SHUTDOWN
REPLICATION SLAVE
REPLICATION CLIENT
LOCK TABLES
PROCESS
程序类:针对 FUNCTION、PROCEDURE、TRIGGER
CREATE
ALTER
DROP
EXCUTE
库和表级别:针对 DATABASE、TABLE
ALTER
CREATE
CREATE VIEW
DROP INDEX
SHOW VIEW
GRANT OPTION:能将自己获得的权限转赠给其他用户
数据操作
SELECT
INSERT
DELETE
UPDATE
字段级别
SELECT(col1,col2,...)
UPDATE(col1,col2,...)
INSERT(col1,col2,...)
所有权限
ALL PRIVILEGES 或 ALL
授权:GRANT
GRANT priv_type [(column_list)],... ON [object_type] priv_level TO 'user'@'host'
[IDENTIFIED BY 'password'] [WITH GRANT OPTION];
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 count
| MAX_UPDATES_PER_HOUR count
| MAX_CONNECTIONS_PER_HOUR count
| MAX_USER_CONNECTIONS count
参考:https://dev.mysql.com/doc/refman/5.7/en/grant.html
范例:
GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO 'someuser'@'somehost‘;
GRANT ALL ON wordpress.* TO wordpress@'192.168.39.%' IDENTIFIED BY 'magedu';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.39.%' IDENTIFIED BY 'magedu'
WITH GRANT OPTION;
取消授权:REVOKE
REVOKE priv_type [(column_list)] [, priv_type [(column_list)]] ... ON
[object_type] priv_level FROM user [, user] ...
参考:https://dev.mysql.com/doc/refman/5.7/en/revoke.html
范例:
REVOKE DELETE ON testdb.* FROM 'testuser'@‘172.16.0.%’;
查看指定用户获得的授权
Help SHOW GRANTS
SHOW GRANTS FOR 'user'@'host';
SHOW GRANTS FOR CURRENT_USER[()];
注意:MariaDB服务进程启动时会读取mysql库中所有授权表至内存
(1) GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效
(2) 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:mysql>FLUSH PRIVILEGES;