专职DBA-MySQL-SQL基础应用
Posted zhouwanchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了专职DBA-MySQL-SQL基础应用相关的知识,希望对你有一定的参考价值。
专职DBA-mysql-SQL基础应用 SQL介绍 结构化查询语言 5.7以后符合SQL92严格模式 通过sql_mode参数来控制 常用的SQL分类 DDL:数据定义语言 DCL:数据控制语言 DML:数据操作语言 DQL:数据查询语言 数据类型 作用:保证数据的准确性和标准性。 种类: 1.数值类型
tinyint :-128~127 int :-2^31~2^31-1 说明:手机号是无法存储到int的。一般是使用char类型来存储收集号 2.字符类型
例如: char(11) 定长的字符串类型,在存储字符串时,最大字符长度11个,立即分配11个字符长度的存储空间,如果存不满,空格填充。 varchar(11) 变长的字符串类型看,最大字符长度11个。在存储字符串时,自动判断字符长度,按需分配存储空间。 enum(‘bj‘,‘tj‘,‘sh‘): 枚举类型,比较适合于将来此列的值是固定范围内的特点,可以使用enum,可以很大程度的优化我们的索引结构。 3.时间类型
DATETIME 范围为从1000-01-01 00:00:00.000000至9999-12-31 23:59:59.999999 TIMESTAMP 1970-01-01 00:00:00.000000 至 2038-01-19 03:14:07.999999 timestamp会受到时区的影响 列值不能为空,也是表设计的规范,尽可能将所有的列设置为非空。可以设置默认值为0 unique key : 唯一键 列值不能重复 unsigned : 无符号 针对数字列,非负数。 其他属性 key : 索引 可以在某列上建立索引,来优化查询。 4.二进制类型
表属性 1.列属性 约束(一般建表时添加) primary key : 主键约束 设置为主键的列,此列的值必须非空且唯一,主键在一个表中只能有一个,但是可以有多个列一起构成。 not null:非空约束 列值不能为空,也是表设计的规范,尽可能将所有的列设置为非空,可以设置默认值为0 unique key:唯一键 列值不能重复 unsigned:无符号 针对数字列,非负数。 其他属性: key : 索引 可以在某列上建立索引,来优化查询,一般是根据需要后添加。 default : 默认值 列中,没有录入值时,会自动使用default的值填充。 auto_increment : 自增长 针对数字列,顺序的自动填充数据(默认是从1开始,将来可以设定起始点和偏移量) comment : 注释 2.表属性 存储引擎:InnoDB(默认存储引擎) 字符集和排序规则: utf8 utf8mb4 字符集:utf8 utf8mb4 校对规则:大小写是否敏感 [[email protected] ~]# mysql -uroot -p -S /tmp/mysql.sock Enter password: DDL应用:数据定义语句 库定义:创建数据库 mysql [(none)]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | world | +--------------------+ 5 rows in set (0.00 sec) mysql [(none)]> create database school; Query OK, 1 row affected (0.00 sec) mysql [(none)]> create schema sch; Query OK, 1 row affected (0.00 sec) mysql [(none)]> show charset; +----------+---------------------------------+---------------------+--------+ | 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 | | gb18030 | China National Standard GB18030 | gb18030_chinese_ci | 4 | +----------+---------------------------------+---------------------+--------+ 41 rows in set (0.00 sec) mysql [(none)]> show charset; 数据库支持的字符集 mysql [(none)]> show collation; 数据库支持的校对规则 mysql [(none)]> create database test charset=utf8; Query OK, 1 row affected (0.00 sec) mysql [(none)]> create database shenzhen charset=utf8mb4 collate=utf8mb4_bin; Query OK, 1 row affected (0.00 sec) mysql [(none)]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sch | | school | | shenzhen | | sys | | test | | world | +--------------------+ 9 rows in set (0.00 sec) 建库规范: 1.库名不能有大写字母 2.建库要加字符集 3.库名不能有数字开头 4.库名要和业务相关 查看建库语句 mysql [(none)]> show create database shenzhen; +----------+------------------------------------------------------------------------------------------+ | Database | Create Database | +----------+------------------------------------------------------------------------------------------+ | shenzhen | CREATE DATABASE `shenzhen` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin */ | +----------+------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) 删除数据库(生产环境中禁止使用) mysql [(none)]> drop database sch; Query OK, 0 rows affected (0.01 sec) mysql [(none)]> drop database school; Query OK, 0 rows affected (0.00 sec) mysql [(none)]> drop database test; Query OK, 0 rows affected (0.00 sec) mysql [(none)]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | shenzhen | | sys | | world | +--------------------+ 6 rows in set (0.00 sec) 修改库定义 修改数据库字符集 mysql [(none)]> create database beijing charset=utf8; Query OK, 1 row affected (0.00 sec) mysql [(none)]> show create database beijing; +----------+------------------------------------------------------------------+ | Database | Create Database | +----------+------------------------------------------------------------------+ | beijing | CREATE DATABASE `beijing` /*!40100 DEFAULT CHARACTER SET utf8 */ | +----------+------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql [(none)]> alter database beijing charset=utf8mb4; Query OK, 1 row affected (0.00 sec) mysql [(none)]> show create database beijing; +----------+---------------------------------------------------------------------+ | Database | Create Database | +----------+---------------------------------------------------------------------+ | beijing | CREATE DATABASE `beijing` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ | +----------+---------------------------------------------------------------------+ 1 row in set (0.00 sec) DQL数据查询语句 mysql [(none)]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | beijing | | mysql | | performance_schema | | shenzhen | | sys | | world | +--------------------+ 7 rows in set (0.00 sec) mysql [(none)]> show create database beijing; +----------+---------------------------------------------------------------------+ | Database | Create Database | +----------+---------------------------------------------------------------------+ | beijing | CREATE DATABASE `beijing` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ | +----------+---------------------------------------------------------------------+ 1 row in set (0.00 sec) 表定义:创建表 create table t1( 列1 属性(数据类型、约束、其他属性), 列2 属性, 列3 属性 )表存数引擎 表字符集; 1.表名小写 2.不能是数字开头 3.注意字符集和存储引擎 4.表名和业务有关 5.选择合适的数据类型 6.每个列都要有注释 7.每个列设置为非空,无法保证非空,用0来填充。 mysql [(none)]> use beijing; Database changed mysql [beijing]> show tables; Empty set (0.00 sec) 打开Aqua开始建表
use beijing; CREATE TABLE stu( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT ‘学号‘, sname VARCHAR(20) NOT NULL COMMENT ‘姓名‘, sage TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ‘年龄‘, sgender ENUM(‘m‘,‘f‘,‘n‘) NOT NULL DEFAULT ‘n‘ COMMENT ‘性别‘, sfz CHAR(18) NOT NULL UNIQUE COMMENT ‘身份证‘, intime TIMESTAMP NOT NULL DEFAULT NOW() COMMENT ‘入学时间‘ ) ENGINE=INNODB CHARSET=utf8mb4 COMMENT ‘学生表‘; mysql [beijing]> show tables; +-------------------+ | Tables_in_beijing | +-------------------+ | stu | +-------------------+ 1 row in set (0.00 sec) mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(20) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +---------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.06 sec) 删除表(生产环境禁止使用) mysql [beijing]> create table t1(id int); Query OK, 0 rows affected (0.03 sec) mysql [beijing]> show tables; +-------------------+ | Tables_in_beijing | +-------------------+ | stu | | t1 | +-------------------+ 2 rows in set (0.00 sec) mysql [beijing]> drop table t1; Query OK, 0 rows affected (0.03 sec) mysql [beijing]> show tables; +-------------------+ | Tables_in_beijing | +-------------------+ | stu | +-------------------+ 1 row in set (0.00 sec) 修改表定义 1.在stu表中添加qq列 mysql [beijing]> alter table stu add qq varchar(20) not null unique comment ‘qq号‘; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(20) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | | qq | varchar(20) | NO | UNI | NULL | | +---------+---------------------+------+-----+-------------------+----------------+ 7 rows in set (0.00 sec) 2.在sname后加微信列 mysql [beijing]> alter table stu add wechat varchar(64) not null unique comment ‘微信号‘ after sname; Query OK, 0 rows affected (0.05 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(20) | NO | | NULL | | | wechat | varchar(64) | NO | UNI | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | | qq | varchar(20) | NO | UNI | NULL | | +---------+---------------------+------+-----+-------------------+----------------+ 8 rows in set (0.00 sec) 3.在id列前加一个新列num mysql [beijing]> alter table stu add num int not null comment ‘数字‘ first; Query OK, 0 rows affected (0.05 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | num | int(11) | NO | | NULL | | | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(20) | NO | | NULL | | | wechat | varchar(64) | NO | UNI | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | | qq | varchar(20) | NO | UNI | NULL | | +---------+---------------------+------+-----+-------------------+----------------+ 9 rows in set (0.01 sec) 4.把刚才添加的新列都删掉(危险操作) mysql [beijing]> alter table stu drop num; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> alter table stu drop wechat; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> alter table stu drop qq; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(20) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +---------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.00 sec) 5.修改sname数据类型的属性 mysql [beijing]> alter table stu modify sname varchar(128) not null; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +---------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(128) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sgender | enum(‘m‘,‘f‘,‘n‘) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +---------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.01 sec) 6.将sgender改为sex 数据类型改为char类型 mysql [beijing]> alter table stu change sgender sex char(1) not null default ‘n‘; Query OK, 0 rows affected (0.05 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql [beijing]> desc stu; +--------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(128) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sex | char(1) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +--------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.01 sec) DQL表属性查询 mysql [(none)]> use beijing; Database changed mysql [beijing]> show tables; +-------------------+ | Tables_in_beijing | +-------------------+ | stu | +-------------------+ 1 row in set (0.00 sec) mysql [beijing]> desc stu; +--------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(128) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sex | char(1) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +--------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.00 sec) mysql [beijing]> show create table stu\\G *************************** 1. row *************************** Table: stu Create Table: CREATE TABLE `stu` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘??‘, `sname` varchar(128) NOT NULL, `sage` tinyint(3) unsigned NOT NULL DEFAULT ‘0‘ COMMENT ‘??‘, `sex` char(1) NOT NULL DEFAULT ‘n‘, `sfz` char(18) NOT NULL COMMENT ‘???‘, `intime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ‘????‘, PRIMARY KEY (`id`), UNIQUE KEY `sfz` (`sfz`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=‘???‘ 1 row in set (0.00 sec) mysql [beijing]> create table stu2 like stu; Query OK, 0 rows affected (0.03 sec) mysql [beijing]> show tables; +-------------------+ | Tables_in_beijing | +-------------------+ | stu | | stu2 | +-------------------+ 2 rows in set (0.00 sec) mysql [beijing]> desc stu2; +--------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(128) | NO | | NULL | | | sage | tinyint(3) unsigned | NO | | 0 | | | sex | char(1) | NO | | n | | | sfz | char(18) | NO | UNI | NULL | | | intime | timestamp | NO | | CURRENT_TIMESTAMP | | +--------+---------------------+------+-----+-------------------+----------------+ 6 rows in set (0.00 sec) DCL应用:grant revoke DML应用:对表中的数据行进行增删改。 以下操作我全部用Aqua操作啦!!!!!!!!!!!!!!!!!!!! insert插入 最标准的insert语句 use beijing; desc stu; insert into stu(id,sname,sage,sex,sfz,intime) values (1,‘zhangsan‘,18,‘m‘,‘1234561‘,now()); select * from stu; 省事的写法 insert into stu values (2,‘lisi‘,18,‘m‘,‘1234562‘,now()); select * from stu; 针对性的录入数据 insert into stu(sname,sfz) values (‘wang5‘,‘1234563‘); select * from stu; 同时录入多行数据 insert into stu(sname,sfz) values (‘zhao6‘,‘1234564‘), (‘qi7‘,‘1234565‘), (‘wang8‘,‘1234566‘); select * from stu; update更改数据 desc stu; select * from stu; update stu set sname=‘zhang3‘ where id=1; update stu set sname=‘li4‘ where id=2; select * from stu; 注意:update语句必须要加where delete删除(危险命令!!!) id sname sage sex sfz intime ----- -------- ------- ------ ------- ------------------ 1 zhang3 18 m 1234561 2019-7-1 上午1:27:03 2 li4 18 m 1234562 2019-7-1 上午1:29:54 3 wang5 0 n 1234563 2019-7-1 上午1:32:11 4 zhao6 0 n 1234564 2019-7-1 上午1:35:25 5 qi7 0 n 1234565 2019-7-1 上午1:35:25 6 wang8 0 n 1234566 2019-7-1 上午1:35:25 delete from stu where id=6; select * from stu; 全表删除 delete from stu; truncate table stu; 区别: delete: DML操作,是逻辑性质删除,逐行进行删除,速度慢。 truncate: DDL操作,对与表段中的数据页进行清空,速度快。 伪删除:用update来替代delete,最终保证业务中查不到(select)即可。 1.添加状态列 alter table stu add state tinyint not null default 1; select * from stu; 2.update代替delete update stu set state=0 where id=5; 3.业务语句查询 select * from stu where state=1; DQL应用(select) 1.select单独使用 mysql [(none)]> select @@port; +--------+ | @@port | +--------+ | 3306 | +--------+ 1 row in set (0.00 sec) mysql [(none)]> select @@basedir; +-------------+ | @@basedir | +-------------+ | /app/mysql | +-------------+ 1 row in set (0.00 sec) mysql [(none)]> select @@datadir; +--------------+ | @@datadir | +--------------+ | /data/mysql | +--------------+ 1 row in set (0.00 sec) mysql [(none)]> select @@socket; +-----------------+ | @@socket | +-----------------+ | /tmp/mysql.sock | +-----------------+ 1 row in set (0.00 sec) mysql [(none)]> select @@server_id; +-------------+ | @@server_id | +-------------+ | 6 | +-------------+ 1 row in set (0.00 sec) 2.select函数 mysql [(none)]> select now(); +---------------------+ | now() | +---------------------+ | 2019-07-01 02:01:36 | +---------------------+ 1 row in set (0.00 sec) mysql [(none)]> select database(); +------------+ | database() | +------------+ | NULL | +------------+ 1 row in set (0.00 sec) mysql [(none)]> select user(); +----------------+ | user() | +----------------+ | root@localhost | +----------------+ 1 row in set (0.00 sec) mysql [(none)]> select concat("hello world"); +-----------------------+ | concat("hello world") | +-----------------------+ | hello world | +-----------------------+ 1 row in set (0.00 sec) mysql [(none)]> select concat(user,"@",host) from mysql.user; +-------------------------+ | concat(user,"@",host) | +-------------------------+ | admin@10.0.0.% | | app@10.0.0.% | | eric@10.0.0.% | | root@10.0.0.% | | mysql.session@localhost | | mysql.sys@localhost | | root@localhost | +-------------------------+ 7 rows in set (0.00 sec) mysql [(none)]> select group_concat(user,"@",host) from mysql.user; +--------------------------------------------------------------------------------------------------------------------+ | group_concat(user,"@",host) | +--------------------------------------------------------------------------------------------------------------------+ | admin@10.0.0.%,app@10.0.0.%,eric@10.0.0.%,root@10.0.0.%,mysql.session@localhost,mysql.sys@localhost,root@localhost | +--------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec) mysql [(none)]> select group_concat(sname,"_",sage) from beijing.stu; +----------------------------------------+ | group_concat(sname,"_",sage) | +----------------------------------------+ | zhang3_18,li4_18,wang5_0,zhao6_0,qi7_0 | +----------------------------------------+ 1 row in set (0.00 sec) 单表子句-from SELECT 列1,列2 FROM 表; SELECT * FROM 表; 查询stu表中,学生姓名和入学时间 mysql [(none)]> select sname,intime from beijing.stu; +--------+---------------------+ | sname | intime | +--------+---------------------+ | zhang3 | 2019-07-01 01:27:03 | | li4 | 2019-07-01 01:29:54 | | wang5 | 2019-07-01 01:32:11 | | zhao6 | 2019-07-01 01:35:25 | | qi7 | 2019-07-01 01:35:25 | +--------+---------------------+ 5 rows in set (0.00 sec) 查询stu中所有的数据(不要对大表进行操作) mysql [(none)]> select * from beijing.stu; +----+--------+------+-----+---------+---------------------+-------+ | id | sname | sage | sex | sfz | intime | state | +----+--------+------+-----+---------+---------------------+-------+ | 1 | zhang3 | 18 | m | 1234561 | 2019-07-01 01:27:03 | 1 | | 2 | li4 | 18 | m | 1234562 | 2019-07-01 01:29:54 | 1 | | 3 | wang5 | 0 | n | 1234563 | 2019-07-01 01:32:11 | 1 | | 4 | zhao6 | 0 | n | 1234564 | 2019-07-01 01:35:25 | 1 | | 5 | qi7 | 0 | n | 1234565 | 2019-07-01 01:35:25 | 0 | +----+--------+------+-----+---------+---------------------+-------+ 5 rows in set (0.00 sec) world ==============>世界 city ===============>城市 country ============>国家 countrylanguage ====>国家语言 city:城市表 DESC city; ID : 城市ID NAME : 城市名 CountryCode : 国家代码,比如中国CHN,美国USA District : 区域 Population : 人口 mysql [(none)]> use world; Database changed mysql [world]> show tables; +-----------------+ | Tables_in_world | +-----------------+ | city | | country | | countrylanguage | +-----------------+ 3 rows in set (0.00 sec) mysql [world]> desc city; +-------------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+----------+------+-----+---------+----------------+ | ID | int(11) | NO | PRI | NULL | auto_increment | | Name | char(35) | NO | | | | | CountryCode | char(3) | NO | MUL | | | | District | char(20) | NO | | | | | Population | int(11) | NO | | 0 | | +-------------+----------+------+-----+---------+----------------+ 5 rows in set (0.00 sec) 单表子句-where select col1,col2 from table where coln 条件; where配合等值查询 --查询中国(CHN)所有城市信息 mysql [world]> select * from city where countrycode=‘CHN‘; --查询北京市的信息 mysql [world]> select * from city where name=‘peking‘; +------+--------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +------+--------+-------------+----------+------------+ | 1891 | Peking | CHN | Peking | 7472000 | +------+--------+-------------+----------+------------+ 1 row in set (0.00 sec) --查询甘肃省所有城市信息 mysql [world]> select * from city where district=‘gansu‘; +------+-----------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +------+-----------+-------------+----------+------------+ | 1913 | Lanzhou | CHN | Gansu | 1565800 | | 2035 | Tianshui | CHN | Gansu | 244974 | | 2064 | Baiyin | CHN | Gansu | 204970 | | 2163 | Wuwei | CHN | Gansu | 133101 | | 2210 | Yumen | CHN | Gansu | 109234 | | 2217 | Jinchang | CHN | Gansu | 105287 | | 2231 | Pingliang | CHN | Gansu | 99265 | +------+-----------+-------------+----------+------------+ 7 rows in set (0.01 sec) where配合比较操作符(> < >= <= <>) --查询世界上少于100人的城市 mysql [world]> select * from city where population<100; +------+-----------+-------------+----------+------------+ | ID | Name | CountryCode | District | Population | +------+-----------+-------------+----------+------------+ | 2912 | Adamstown | PCN | – | 42 | +------+-----------+-------------+----------+------------+ 1 row in set (0.01 sec) where配合逻辑运算符(and or) --中国人口数量大于500w的城市 mysql [world]> select * from city where countrycode=‘CHN‘ and population>5000000; +------+-----------+-------------+-----------+------------+ | ID | Name | CountryCode | District | Population | +------+-----------+-------------+-----------+------------+ | 1890 | Shanghai | CHN | Shanghai | 9696300 | | 1891 | Peking | CHN | Peking | 7472000 | | 1892 | Chongqing | CHN | Chongqing | 6351600 | | 1893 | Tianjin | CHN | Tianjin | 5286800 | +------+-----------+-------------+-----------+------------+ 4 rows in set (0.00 sec) --中国或美国城市信息 mysql [world]> select * from city where countrycode=‘CHN‘ or countrycode=‘USA‘; where配合模糊查询 --查询省的名字前面带guang开头的城市 mysql [world]> select * from city where district like ‘guang%‘; where配合in语句 --中国或美国城市信息 mysql [world]> select * from city where countrycode in (‘CHN‘,‘USA‘); where配合between and --查询世界上人口数量大于100w小于200w的城市信息 mysql [world]> select * from city where population > 1000000 and population < 2000000; mysql [world]> select * from city where population between 1000000 and 2000000; group by + 常用聚合函数 作用:根据by后面的条件进行分组,方便统计,by后面跟一个列或多个列 常用聚合函数 max() : 最大值 min() : 最小值 avg() : 平均值 sum() : 总和 count() : 个数 group_concat() : 列转行 --统计世界上每个国家的总人口数 mysql [world]> select countrycode,SUM(population) from city group by countrycode; --统计中国各个省的总人口数量 mysql [world]> select district,SUM(population) from city where countrycode=‘CHN‘ group by district; --统计世界上每个国家的城市数量 mysql [world]> select countrycode,count(id) from city group by countrycode; having where|group|having --统计中国每个省的总人口数,只打印总人口数小于100w mysql [world]> select district,SUM(population) -> from city -> where countrycode=‘CHN‘ -> group by district -> having SUM(population) < 1000000; +----------+-----------------+ | district | SUM(population) | +----------+-----------------+ | Hainan | 557120 | | Ningxia | 802362 | | Qinghai | 700200 | | Tibet | 120000 | +----------+-----------------+ 4 rows in set (0.01 sec) order by + limit 作用:实现排序,by后添加条件列 --查看中国所有的城市,并按人口数进行排序(从大到小) mysql [world]> select * from city where countrycode=‘CHN‘ order by population desc; --统计中国各个省的总人口数量,按照总人口从大到小排序。 mysql [world]> select district as 省,SUM(population) as 总人口 -> from city -> where countrycode=‘CHN‘ -> group by district -> order by 总人口 desc; --统计中国,每个省的总人口,找出总人口大于500w的,并按总人口从大到小排序,只显示前三名。 mysql [world]> SELECT district,SUM(population) FROM city -> WHERE countrycode=‘CHN‘ -> GROUP BY district -> HAVING SUM(population)>5000000 -> ORDER BY SUM(population) DESC -> LIMIT 3; +--------------+-----------------+ | district | SUM(population) | +--------------+-----------------+ | Liaoning | 15079174 | | Shandong | 12114416 | | Heilongjiang | 11628057 | +--------------+-----------------+ 3 rows in set (0.00 sec) LIMIT N,M --->跳过N,显示一共M行 LIMIT 5,5 mysql [world]> SELECT district,SUM(population) FROM city -> WHERE countrycode=‘CHN‘ -> GROUP BY district -> HAVING SUM(population)>5000000 -> ORDER BY SUM(population) DESC -> LIMIT 5,5; +-----------+-----------------+ | district | SUM(population) | +-----------+-----------------+ | Guangdong | 9510263 | | Hubei | 8547585 | | Jilin | 7826824 | | Peking | 7569168 | | Sichuan | 7456867 | +-----------+-----------------+ 5 rows in set (0.00 sec) distinct去重复 mysql [world]> select countrycode from city; mysql [world]> select count(countrycode) from city; +--------------------+ | count(countrycode) | +--------------------+ | 4079 | +--------------------+ 1 row in set (0.00 sec) mysql [world]> select distinct(countrycode) from city; mysql [world]> select count(distinct(countrycode)) from city; +------------------------------+ | count(distinct(countrycode)) | +------------------------------+ | 232 | +------------------------------+ 1 row in set (0.00 sec) 联合查询-union all --中国或美国城市信息 mysql [world]> select * from city where countrycode in(‘CHN‘,‘USA‘); select * from city where countrycode=‘CHN‘ union all select * from city where countrycode=‘USA‘; 说明: 一般情况下,我们会将IN或者OR语句,改写成UNION ALL来提高性能。 UNION 去重复 UNION ALL 不去重复 多表连接查询-join 按需求创建一下表结构 [[email protected] ~]# mysql -uroot -p -S /tmp/mysql.sock Enter password: mysql [(none)]> create database school charset=utf8mb4; Query OK, 1 row affected (0.00 sec) mysql [(none)]> use school; Database changed student 学生表 sno 学号 sname 学生姓名 sage 学生年龄 ssex 学生性别 teacher 教师表 tno 教师编号 tname 教师名字 course 课程表 cno 课程编号 cname 课程名字 tno 教师编号 score 成绩表 sno 学号 cno 课程编号 score 成绩 --项目构建 mysql [(none)]> drop database school; Query OK, 0 rows affected (0.00 sec) mysql [(none)]> create database school charset=utf8mb4; Query OK, 1 row affected (0.00 sec) 打开Aqua USE school; CREATE TABLE student( sno INT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT ‘学号‘, sname VARCHAR(20) NOT NULL COMMENT ‘姓名‘, sage TINYINT UNSIGNED NOT NULL COMMENT ‘年龄‘, ssex ENUM(‘f‘,‘m‘) NOT NULL DEFAULT ‘m‘ COMMENT ‘性别‘ )ENGINE=INNODB CHARSET=utf8; CREATE TABLE course( cno INT NOT NULL PRIMARY KEY COMMENT ‘课程编号‘, cname VARCHAR(20) NOT NULL COMMENT ‘课程名字‘, tno INT NOT NULL COMMENT ‘教师编号‘ )ENGINE=INNODB CHARSET utf8; CREATE TABLE sc ( sno INT NOT NULL COMMENT ‘学号‘, cno INT NOT NULL COMMENT ‘课程编号‘, score INT NOT NULL DEFAULT 0 COMMENT ‘成绩‘ )ENGINE=INNODB CHARSET=utf8; CREATE TABLE teacher( tno INT NOT NULL PRIMARY KEY COMMENT ‘教师编号‘, tname VARCHAR(20) NOT NULL COMMENT ‘教师名字‘ )ENGINE=INNODB CHARSET utf8; INSERT INTO student(sno,sname,sage,ssex) VALUES (1,‘zhang3‘,18,‘m‘); INSERT INTO student(sno,sname,sage,ssex) VALUES (2,‘zhang4‘,18,‘m‘), (3,‘li4‘,18,‘m‘), (4,‘wang5‘,19,‘f‘); INSERT INTO student VALUES (5,‘zh4‘,18,‘m‘), (6,‘zhao4‘,18,‘m‘), (7,‘ma6‘,19,‘f‘); INSERT INTO student(sname,sage,ssex) VALUES (‘oldboy‘,20,‘m‘), (‘oldgirl‘,20,‘f‘), (‘oldp‘,25,‘m‘); INSERT INTO teacher(tno,tname) VALUES (101,‘oldboy‘), (102,‘hesw‘), (103,‘oldguo‘); DESC course; INSERT INTO course(cno,cname,tno) VALUES (1001,‘linux‘,101), (1002,‘python‘,102), (1003,‘mysql‘,103); DESC sc; INSERT INTO sc(sno,cno,score) VALUES (1,1001,80), (1,1002,59), (2,1002,90), (2,1003,100), (3,1001,99), (3,1003,40), (4,1001,79), (4,1002,61), (4,1003,99), (5,1003,40), (6,1001,89), (6,1003,77), (7,1001,67), (7,1003,82), (8,1001,70), (9,1003,80), (10,1003,96); SELECT * FROM student; SELECT * FROM teacher; SELECT * FROM course; SELECT * FROM sc; 表a join 表b---》横向拼成一行
查询张三的家庭住址 select a.name,b.adders from a join b on a.id=b.id where a.name="zhangsan"; 查询一下世界上人口数量小于100人的城市名和国家名 use world; select b.name,a.name,a.population from city as a join country as b on b.code=a.countrycode where a.population<100; 查询城市shenyang,城市人口,所在国家名(name)及国土面积(SurfaceArea) select a.name,a.population,b.name,b.SurfaceArea from city as a join country as b on a.countrycode=b.code where a.name=‘shenyang‘; 别名(列别名,表别名) select b.name as bn, a.name as an, a.Population as ap, b.SurfaceArea as bs from city as a join country as b on a.countrycode=b.code where a.name=‘shenyang‘; 多表SQL练习题 统计zhang3学习了几门课 use school; select st.sname,count(sc.cno) from student as st join sc on st.sno=sc.sno where st.sname="zhang3"; 查询zhang3学习的课程名称有哪些 select st.sname,group_concat(co.cname) from student as st join sc on st.sno=sc.sno join course as co on sc.cno=co.cno where st.sname="zhang3"; 查询oldguo老师教的学生名 select te.tname,GROUP_CONCAT(st.sname) from student as st join sc on st.sno=sc.sno join course as co on sc.cno=co.cno join teacher as te on co.tno=te.tno where te.tname=‘oldguo‘; 查询oldguo所教课程的平均分数 select te.tname,AVG(sc.score) from teacher as te join course as co on te.tno=co.tno join sc on co.cno=sc.cno where te.tname=‘oldguo‘; 每位老师所教课程的平均分,并按平均分排序 select te.tname,AVG(sc.score) from teacher as te join course as co on te.tno=co.tno join sc on co.cno=sc.cno group by te.tname order by AVG(sc.score) desc; 查询oldguo所教的不及格的学生姓名 select te.tname,st.sname,sc.score from teacher as te join course as co on te.tno=co.tno join sc on co.cno=sc.cno join student as st on sc.sno=st.sno where te.tname=‘oldguo‘ and sc.score<60; 查询所有老师所教学生不及格的信息 select te.tname,st.sname,sc.score from teacher as te join course as co on te.tno=co.tno join sc on co.cno=sc.cno join student as st on sc.sno=st.sno where sc.score<60; 综合练习 1.查询平均成绩大于60分的同学的学号和平均成绩。 2.查询所有同学的学号、姓名、选课数、总成绩。 3.查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分。 4.统计各位老师,所教课程的及格率。 5.查询每门课程被选修的学生数。 6.查询出只选修了一门课程的全部学生的学号和姓名。 7.查询选修课程门数超过1门的学生信息。 8.统计每门课程:优秀(85分以上),良好(70-85),一般(60-70),不及格(小于60)的学生列表。 9.查询平均成绩大于85的所有学生的学号、姓名和平均成绩。 information_schema.tables视图 [[email protected] ~]# mysql -uroot -p -S /tmp/mysql.sock Enter password: mysql [(none)]> desc information_schema.tables; TABLE_SCHEMA ---->库名 TABLE_NAME ---->表名 ENGINE ---->引擎 TABLE_ROWS ---->表的行数 AVG_ROW_LENGTH ---->表中行的平均行(字节) INDEX_LENGTH ---->索引的占用空间大小(字节) information_schema.tables它存储的是整个数据库所有的元数据信息 元数据:表名,表属性,列,列属性,权限等等。 查询整个数据库中所有库和表的对应信息 select table_schema,group_concat(table_name) from information_schema.tables group by table_schema; 统计所有库下的表个数(张数) select table_schema,count(table_name) from information_schema.tables group by table_schema; 查询所有innodb引擎的表及所在的库 select table_schema,table_name,engine from information_schema.tables where engine=‘innodb‘; [[email protected] ~]# du -sh /data 520M /data 统计world数据库下每张表的磁盘空间占用 SELECT table_name,CONCAT((TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024," KB") AS size_KB FROM information_schema.tables WHERE TABLE_SCHEMA=‘world‘; 统计所有数据库的总的磁盘空间占用 SELECT TABLE_SCHEMA, CONCAT(SUM(TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024," KB") AS Total_KB FROM information_schema.tables GROUP BY table_schema; mysql -uroot -p123 -e "SELECT TABLE_SCHEMA,CONCAT(SUM(TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024,‘ KB‘) AS Total_KB FROM information_schema.tables GROUP BY table_schema;" [[email protected] ~]# mysql -uroot -p123 -e "SELECT TABLE_SCHEMA,CONCAT(SUM(TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024,‘ KB‘) AS Total_KB FROM information_schema.tables GROUP BY table_schema;" mysql: [Warning] Using a password on the command line interface can be insecure. +--------------------+--------------+ | TABLE_SCHEMA | Total_KB | +--------------------+--------------+ | beijing | 47.9961 KB | | information_schema | NULL | | mysql | 2323.7598 KB | | performance_schema | 0.0000 KB | | school | 63.9814 KB | | sys | 15.9961 KB | | world | 779.7744 KB | +--------------------+--------------+ 生成整个数据库下的所有表的单独备份语句 模板语句 mysqldump -uroot -p123 world city > /tmp/world_city.sql SELECT CONCAT("mysqldump -uroot -p123 ",table_schema," ",table_name," > /backup/",table_schema,"_",table_name,".sql") FROM information_schema.tables INTO OUTFILE ‘/tmp/bak.sh‘; [[email protected] ~]# vim /etc/my.cnf [mysqld] USER=mysql basedir=/app/mysql datadir=/DATA/mysql/ server_id=1 PORT=3306 SOCKET=/tmp/mysql.sock secure-file-priv=/tmp <===安全目录授权 [mysql] SOCKET=/tmp/mysql.sock [[email protected] ~]# systemctl restart mysqld mysqldump -uroot -p123 world city > /tmp/world_city.sql SELECT CONCAT("mysqldump -uroot -p123 ",table_schema," ",table_name," > /backup/",table_schema,"_",table_name,".sql") FROM information_schema.tables INTO OUTFILE ‘/tmp/bak.sh‘; [[email protected] ~]# ls -l /tmp/ total 212 -rw-rw-rw- 1 mysql mysql 30899 Jun 10 21:13 bak.sh srwxrwxrwx 1 mysql mysql 0 Jun 10 21:08 mysql.sock -rw------- 1 mysql mysql 5 Jun 10 21:08 mysql.sock.lock -rw-r--r-- 1 root root 179243 Jun 10 19:59 world_city.sql [[email protected] ~]# tail -3 /tmp/bak.sh mysqldump -uroot -p123 world city > /backup/world_city.sql mysqldump -uroot -p123 world country > /backup/world_country.sql mysqldump -uroot -p123 world countrylanguage > /backup/world_countrylanguage.sql [[email protected] ~]# sh /tmp/bak.sh [[email protected] ~]# ls /backup/ | wc -l 239 [[email protected] ~]# ls -l /backup/world_* -rw-r--r-- 1 root root 179243 Jun 22 05:56 /backup/world_city.sql -rw-r--r-- 1 root root 28329 Jun 22 05:56 /backup/world_countrylanguage.sql -rw-r--r-- 1 root root 38954 Jun 22 05:56 /backup/world_country.sql 将来你不备份谁写在 where 后面 select CONCAT("mysqldump -uroot -p123 ",table_schema," ",table_name," > /backup/",table_schema,"_",table_name,".sql") from information_schema.tables where table_schema not in("information_schema","performance_schema","sys") into outfile ‘/tmp/bak.sh‘; 每天进行备份,然后进行打包,传到我们的专门备份服务器上去。 107张表,都需要执行以下2条语句 alter table world.city discard tablespace; alter table world.city import tablespace; SELECT CONCAT("alter table ",table_schema,".",table_name," discard tablespace") FROM information_schema.tables WHERE table_schema=‘world‘ INTO OUTFILE ‘/tmp/dis.sql‘; select concat("alter table ",table_schema,".",table_name," import tablespace") from information_schema.tables where table_schema=‘world‘ into outfile ‘/tmp/import.sql‘; [[email protected] ~]# cat /tmp/dis.sql alter table world.city discard tablespace alter table world.country discard tablespace alter table world.countrylanguage discard tablespace show 命令 show databases; #查看所有数据库 show tables; #查看当前库的所有表 show tables from world; #查看某个指定库下的表 show create database world; #查看建库语句 show create table world.city; #查看建表语句 show grants for [email protected]‘localhost‘; #查看用户的权限信息 show charset; #查看字符集 show collation; #查看校对规则 show processlist; #查看数据库连接情况 show full processlist; show index from world.city; #表的索引情况 show status; #数据库状态查看 show status like ‘%lock%‘; #模糊查询数据库某些状态 show variables; #查看所有配置信息 show variables like ‘%lock%‘; #查看部分配置信息 show engines; #查看支持的所有的存储引擎 show engine innodb status\\G #查看InnoDB引擎相关的状态信息 show binary logs; #列举所有的二进制日志 show master status; #查看数据库的日志位置信息 show binlog events in ‘mysql-bin.000001‘\\G; #查看二进制日志事件 show slave status\\G #查看从库状态 show relaylog events #查看从库relaylog事件信息 desc world.city;(show columns from world.city;) #查看表的列定义信息 官方文档http://dev.mysql.com/doc/refman/5.7/en/show.html
以上是关于专职DBA-MySQL-SQL基础应用的主要内容,如果未能解决你的问题,请参考以下文章