从入门到删库跑路的过程

数据库简介

从入门到删库跑路的过程_第1张图片

数据库的发展史

  • 萌芽阶段:文件系统
    • 使用磁盘文件来存储数据
  • 初级阶段:第一代数据库
    • 出现了网状模型、层次模型的数据库
  • 中级阶段:第二代数据库
    • 关系型数据库和结构化查询语言
  • 高级阶段:新一代数据库
    • 关系-对象 型数据库

NoSQL非关系数据库:Not Only SQL

数据库管理系统

数据库是数据的汇集,它以一定的组织形式存于存储介质上

DBMS是管理数据库的系统软件,它实现数据库系统的各种功能。是数据库系统的核心

DBA:负责数据库的规划、设计、协调、维护和管理等工作

应用程序指以数据库为基础的应用程序

数据库管理系统的优点

  • 相互关联的数据的集合
  • 较少的数据冗余
  • 程序与数据相互独立
  • 保证数据的安全、可靠
  • 最大限度地保证数据的正确性
  • 数据可以并发使用并能同时保证一致性

MYSQL(马云生气了)系列

官方网址:

https://www.mysql.com/
http://mariadb.org/
https://www.percona.com

官方文档:

https://dev.mysql.com/doc/
https://mariadb.com/kb/en/
https://www.percona.com/software/mysql-database/percona-server

版本演变:
MySQL:5.1 --> 5.5 --> 5.6 --> 5.7 -->8.0
MariaDB:5.5 -->10.0–> 10.1 --> 10.2 --> 10.3

MYSQL的特性

  • 插件式存储引擎:也称为“表类型”,存储管理器有多种实现版本,功能和特性可能均略有差别;用户可根据需要灵活选择,Mysql5.5.5开始innoDB引擎是MYSQL默认引擎
    MyISAM ==> Aria
    InnoDB ==> XtraDB
  • 单进程,多线程
  • 诸多扩展和新特性
  • 提供了较多测试组件
  • 开源

安装MYSQL

Mariadb安装方式:

  • 源代码:编译安装
  • 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
  • 程序包管理器管理的程序包
  • CentOS 安装光盘
    项目官方:https://downloads.mariadb.org/mariadb/repositories/
    国内镜像:https://mirrors.tuna.tsinghua.edu.cn/mariadb/yum/
    https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/

centos6是最后自带mysql的版本了,在centos7中默认的是mariadb

centos 7的mariadb的安装yum源

[mariadb]
name=MariaDBbaseurl=https://mirrors.tuna.tsinghua.edu.cn/mariadb/yum/10.2/centos74-amd64/
gpgcheck=0
# 安装方法
sudo yum install MariaDB-server MariaDB-client

centos7中默认版本为5.5.64

[root@localhost ~]# yum info mariadb
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Available Packages
Name        : mariadb
Arch        : x86_64
Epoch       : 1
Version     : 5.5.64
Release     : 1.el7
Size        : 8.7 M
Repo        : base
Summary     : A community developed branch of MySQL
URL         : http://mariadb.org
License     : GPLv2 with exceptions and LGPLv2 and BSD
Description : MariaDB is a community developed branch of MySQL.
            : MariaDB is a multi-user, multi-threaded SQL database server.
            : It is a client/server implementation consisting of a server daemon (mysqld)
            : and many different client programs and libraries. The base package
            : contains the standard MariaDB/MySQL client programs and generic MySQL files.

配置yum源安装mariadb

[root@localhost ~]# vim /etc/yum.repos.d/mariadb.repo

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1


[root@localhost ~]# yum repolist
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
repo id                                      repo name                                    status
!base                                        Base                                         10,097
epel                                         Epel                                         13,329
mariadb                                      MariaDB                                          95
repolist: 23,521

文件包内容

[root@localhost ~]# rpm -ql MariaDB-server
/etc/init.d/mysql
/etc/logrotate.d/mysql
/etc/my.cnf.d
/etc/my.cnf.d/enable_encryption.preset
/etc/my.cnf.d/server.cnf
/etc/security/user_map.conf
/lib64/security/pam_user_map.so
/usr/bin/aria_chk
/usr/bin/aria_dump_log
/usr/bin/aria_ftdump
/usr/bin/aria_pack
/usr/bin/aria_read_log
/usr/bin/galera_new_cluster
/usr/bin/galera_recovery
/usr/bin/innochecksum
/usr/bin/mariadb-service-convert
/usr/bin/my_print_defaults
/usr/bin/myisam_ftdump
/usr/bin/myisamchk
/usr/bin/myisamlog
/usr/bin/myisampack
/usr/bin/mysql_convert_table_format
/usr/bin/mysql_fix_extensions
/usr/bin/mysql_install_db
/usr/bin/mysql_secure_installation
/usr/bin/mysql_setpermission
/usr/bin/mysql_tzinfo_to_sql
/usr/bin/mysql_upgrade
/usr/bin/mysqld_multi
/usr/bin/mysqld_safe
/usr/bin/mysqld_safe_helper
/usr/bin/mysqldumpslow
/usr/bin/mysqlhotcopy
/usr/bin/perror
/usr/bin/replace
/usr/bin/resolve_stack_dump
/usr/bin/resolveip
/usr/bin/wsrep_sst_common
/usr/bin/wsrep_sst_mariabackup
/usr/bin/wsrep_sst_mysqldump
/usr/bin/wsrep_sst_rsync
/usr/bin/wsrep_sst_rsync_wan
/usr/bin/wsrep_sst_xtrabackup
/usr/bin/wsrep_sst_xtrabackup-v2
/usr/lib/systemd/system/mariadb.service
/usr/lib/systemd/system/[email protected]
/usr/lib/systemd/system/[email protected]
/usr/lib/systemd/system/[email protected]/use_galera_new_cluster.conf
/usr/lib/sysusers.d
/usr/lib/sysusers.d/mariadb.conf
/usr/lib/tmpfiles.d/mariadb.conf
/usr/lib64/libmysqld.so
/usr/lib64/libmysqld.so.19
/usr/lib64/mysql
/usr/lib64/mysql/plugin
/usr/lib64/mysql/plugin/auth_ed25519.so
/usr/lib64/mysql/plugin/auth_pam.so
/usr/lib64/mysql/plugin/auth_socket.so
/usr/lib64/mysql/plugin/disks.so
/usr/lib64/mysql/plugin/file_key_management.so
/usr/lib64/mysql/plugin/ha_archive.so
/usr/lib64/mysql/plugin/ha_blackhole.so
/usr/lib64/mysql/plugin/ha_federated.so
/usr/lib64/mysql/plugin/ha_federatedx.so
/usr/lib64/mysql/plugin/ha_mroonga.so
/usr/lib64/mysql/plugin/ha_sphinx.so
/usr/lib64/mysql/plugin/ha_spider.so
/usr/lib64/mysql/plugin/handlersocket.so
/usr/lib64/mysql/plugin/locales.so
/usr/lib64/mysql/plugin/metadata_lock_info.so
/usr/lib64/mysql/plugin/query_cache_info.so
/usr/lib64/mysql/plugin/query_response_time.so
/usr/lib64/mysql/plugin/semisync_master.so
/usr/lib64/mysql/plugin/semisync_slave.so
/usr/lib64/mysql/plugin/server_audit.so
/usr/lib64/mysql/plugin/simple_password_check.so
/usr/lib64/mysql/plugin/sql_errlog.so
/usr/lib64/mysql/plugin/wsrep_info.so
/usr/sbin/mysqld
/usr/sbin/rcmysql
/usr/share/doc/MariaDB-server-10.2.32
/usr/share/doc/MariaDB-server-10.2.32/COPYING
/usr/share/doc/MariaDB-server-10.2.32/COPYING.AGPLv3
/usr/share/doc/MariaDB-server-10.2.32/COPYING.GPLv2
/usr/share/doc/MariaDB-server-10.2.32/CREDITS
/usr/share/doc/MariaDB-server-10.2.32/EXCEPTIONS-CLIENT
/usr/share/doc/MariaDB-server-10.2.32/INSTALL-BINARY
/usr/share/doc/MariaDB-server-10.2.32/PATENTS
/usr/share/doc/MariaDB-server-10.2.32/README-wsrep
/usr/share/doc/MariaDB-server-10.2.32/README.md
/usr/share/doc/MariaDB-server-10.2.32/THIRDPARTY
/usr/share/man/man1
/usr/share/man/man1/aria_chk.1.gz
/usr/share/man/man1/aria_dump_log.1.gz
/usr/share/man/man1/aria_ftdump.1.gz
/usr/share/man/man1/aria_pack.1.gz
/usr/share/man/man1/aria_read_log.1.gz
/usr/share/man/man1/galera_new_cluster.1.gz
/usr/share/man/man1/galera_recovery.1.gz
/usr/share/man/man1/innochecksum.1.gz
/usr/share/man/man1/mariabackup.1.gz
/usr/share/man/man1/mariadb-service-convert.1.gz
/usr/share/man/man1/mbstream.1.gz
/usr/share/man/man1/my_print_defaults.1.gz
/usr/share/man/man1/myisam_ftdump.1.gz
/usr/share/man/man1/myisamchk.1.gz
/usr/share/man/man1/myisamlog.1.gz
/usr/share/man/man1/myisampack.1.gz
/usr/share/man/man1/mysql.server.1.gz
/usr/share/man/man1/mysql_convert_table_format.1.gz
/usr/share/man/man1/mysql_fix_extensions.1.gz
/usr/share/man/man1/mysql_install_db.1.gz
/usr/share/man/man1/mysql_ldb.1.gz
/usr/share/man/man1/mysql_secure_installation.1.gz
/usr/share/man/man1/mysql_setpermission.1.gz
/usr/share/man/man1/mysql_tzinfo_to_sql.1.gz
/usr/share/man/man1/mysql_upgrade.1.gz
/usr/share/man/man1/mysqld_multi.1.gz
/usr/share/man/man1/mysqld_safe.1.gz
/usr/share/man/man1/mysqld_safe_helper.1.gz
/usr/share/man/man1/mysqldumpslow.1.gz
/usr/share/man/man1/mysqlhotcopy.1.gz
/usr/share/man/man1/perror.1.gz
/usr/share/man/man1/replace.1.gz
/usr/share/man/man1/resolve_stack_dump.1.gz
/usr/share/man/man1/resolveip.1.gz
/usr/share/man/man1/wsrep_sst_common.1.gz
/usr/share/man/man1/wsrep_sst_mariabackup.1.gz
/usr/share/man/man1/wsrep_sst_mysqldump.1.gz
/usr/share/man/man1/wsrep_sst_rsync.1.gz
/usr/share/man/man1/wsrep_sst_rsync_wan.1.gz
/usr/share/man/man1/wsrep_sst_xtrabackup-v2.1.gz
/usr/share/man/man1/wsrep_sst_xtrabackup.1.gz
/usr/share/man/man8
/usr/share/man/man8/mysqld.8.gz
/usr/share/mysql
/usr/share/mysql/binary-configure
/usr/share/mysql/czech
/usr/share/mysql/czech/errmsg.sys
/usr/share/mysql/danish
/usr/share/mysql/danish/errmsg.sys
/usr/share/mysql/dutch
/usr/share/mysql/dutch/errmsg.sys
/usr/share/mysql/english
/usr/share/mysql/english/errmsg.sys
/usr/share/mysql/errmsg-utf8.txt
/usr/share/mysql/estonian
/usr/share/mysql/estonian/errmsg.sys
/usr/share/mysql/fill_help_tables.sql
/usr/share/mysql/french
/usr/share/mysql/french/errmsg.sys
/usr/share/mysql/german
/usr/share/mysql/german/errmsg.sys
/usr/share/mysql/greek
/usr/share/mysql/greek/errmsg.sys
/usr/share/mysql/hindi
/usr/share/mysql/hindi/errmsg.sys
/usr/share/mysql/hungarian
/usr/share/mysql/hungarian/errmsg.sys
/usr/share/mysql/install_spider.sql
/usr/share/mysql/italian
/usr/share/mysql/italian/errmsg.sys
/usr/share/mysql/japanese
/usr/share/mysql/japanese/errmsg.sys
/usr/share/mysql/korean
/usr/share/mysql/korean/errmsg.sys
/usr/share/mysql/magic
/usr/share/mysql/maria_add_gis_sp.sql
/usr/share/mysql/maria_add_gis_sp_bootstrap.sql
/usr/share/mysql/my-huge.cnf
/usr/share/mysql/my-innodb-heavy-4G.cnf
/usr/share/mysql/my-large.cnf
/usr/share/mysql/my-medium.cnf
/usr/share/mysql/my-small.cnf
/usr/share/mysql/mysql-log-rotate
/usr/share/mysql/mysql.server
/usr/share/mysql/mysql_performance_tables.sql
/usr/share/mysql/mysql_system_tables.sql
/usr/share/mysql/mysql_system_tables_data.sql
/usr/share/mysql/mysql_test_data_timezone.sql
/usr/share/mysql/mysql_test_db.sql
/usr/share/mysql/mysql_to_mariadb.sql
/usr/share/mysql/mysqld_multi.server
/usr/share/mysql/norwegian
/usr/share/mysql/norwegian-ny
/usr/share/mysql/norwegian-ny/errmsg.sys
/usr/share/mysql/norwegian/errmsg.sys
/usr/share/mysql/policy
/usr/share/mysql/policy/apparmor
/usr/share/mysql/policy/apparmor/README
/usr/share/mysql/policy/apparmor/usr.sbin.mysqld
/usr/share/mysql/policy/apparmor/usr.sbin.mysqld.local
/usr/share/mysql/policy/selinux
/usr/share/mysql/policy/selinux/README
/usr/share/mysql/policy/selinux/mariadb-server.fc
/usr/share/mysql/policy/selinux/mariadb-server.te
/usr/share/mysql/policy/selinux/mariadb.pp
/usr/share/mysql/policy/selinux/mariadb.te
/usr/share/mysql/polish
/usr/share/mysql/polish/errmsg.sys
/usr/share/mysql/portuguese
/usr/share/mysql/portuguese/errmsg.sys
/usr/share/mysql/romanian
/usr/share/mysql/romanian/errmsg.sys
/usr/share/mysql/russian
/usr/share/mysql/russian/errmsg.sys
/usr/share/mysql/serbian
/usr/share/mysql/serbian/errmsg.sys
/usr/share/mysql/slovak
/usr/share/mysql/slovak/errmsg.sys
/usr/share/mysql/spanish
/usr/share/mysql/spanish/errmsg.sys
/usr/share/mysql/swedish
/usr/share/mysql/swedish/errmsg.sys
/usr/share/mysql/systemd
/usr/share/mysql/systemd/mariadb.service
/usr/share/mysql/systemd/[email protected]
/usr/share/mysql/systemd/use_galera_new_cluster.conf
/usr/share/mysql/ukrainian
/usr/share/mysql/ukrainian/errmsg.sys
/usr/share/mysql/wsrep.cnf
/usr/share/mysql/wsrep_notify

启动服务和查看端口

[root@localhost ~]# systemctl enable --now mariadb
Created symlink from /etc/systemd/system/mysql.service to /usr/lib/systemd/system/mariadb.service.
Created symlink from /etc/systemd/system/mysqld.service to /usr/lib/systemd/system/mariadb.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.

######################
[root@localhost ~]# ss -ntl
State      Recv-Q Send-Q   Local Address:Port                  Peer Address:Port              
                 
LISTEN     0      80                [::]:3306                          [::]:*                  

查看客户端包

[root@localhost ~]# which mysql
/usr/bin/mysql
[root@localhost ~]# rpm -qf /usr/bin/mysql
MariaDB-client-10.2.32-1.el7.centos.x86_64

连接数据库

# 默认没有密码
[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.2.32-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)]> exit
Bye

############################################################################

[root@localhost ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.2.32-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)]> exit
Bye

Mariadb客户端相关命令

MariaDB [(none)]> \h

General information about MariaDB can be found at
http://mariadb.org

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
edit      (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
system    (\!) Execute a system shell command.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

For server side help, type 'help contents'

查看服务器信息

MariaDB [(none)]> \s
--------------
mysql  Ver 15.1 Distrib 10.2.32-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:		10
Current database:	
# 账号名加@客户端主机地址
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		10.2.32-MariaDB MariaDB Server
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
# 在同一台电脑上利用socket套接字文件进行通信
UNIX socket:		/var/lib/mysql/mysql.sock
Uptime:			5 min 55 sec

Threads: 7  Questions: 8  Slow queries: 0  Opens: 17  Flush tables: 1  Open tables: 11  Queries per second avg: 0.022
--------------

查看套接字文件/var/lib/mysql/mysql.sock

[root@localhost ~]# ll /var/lib/mysql/mysql.sock
srwxrwxrwx 1 mysql mysql 0 Jun 22 20:21 /var/lib/mysql/mysql.sock
# 在同一台主机中利用套接字文件,可以省去tcp协议的封装与解封装的过程
# 真正跨网络还是应该走tcp协议

实例 instance

多实例的数据库错开端口号,一般测试环境使用

查看数据库文件/var/lib/mysql

[root@localhost ~]# cd /var/lib/mysql/
[root@localhost mysql]# ls
aria_log.00000001  ibdata1      ibtmp1             mysql               tc.log
aria_log_control   ib_logfile0  localhost.pid      mysql.sock          test
ib_buffer_pool     ib_logfile1  multi-master.info  performance_schema
[root@localhost mysql]# cd mysql/
[root@localhost mysql]# ls
columns_priv.frm    help_category.MYD       plugin.MYD         tables_priv.MYI
columns_priv.MYD    help_category.MYI       plugin.MYI         table_stats.frm
columns_priv.MYI    help_keyword.frm        proc.frm           table_stats.MYD
column_stats.frm    help_keyword.MYD        proc.MYD           table_stats.MYI
column_stats.MYD    help_keyword.MYI        proc.MYI           time_zone.frm
column_stats.MYI    help_relation.frm       procs_priv.frm     time_zone_leap_second.frm
db.frm              help_relation.MYD       procs_priv.MYD     time_zone_leap_second.MYD
db.MYD              help_relation.MYI       procs_priv.MYI     time_zone_leap_second.MYI
db.MYI              help_topic.frm          proxies_priv.frm   time_zone.MYD
db.opt              help_topic.MYD          proxies_priv.MYD   time_zone.MYI
event.frm           help_topic.MYI          proxies_priv.MYI   time_zone_name.frm
event.MYD           host.frm                roles_mapping.frm  time_zone_name.MYD
event.MYI           host.MYD                roles_mapping.MYD  time_zone_name.MYI
func.frm            host.MYI                roles_mapping.MYI  time_zone_transition.frm
func.MYD            index_stats.frm         servers.frm        time_zone_transition.MYD
func.MYI            index_stats.MYD         servers.MYD        time_zone_transition.MYI
general_log.CSM     index_stats.MYI         servers.MYI        time_zone_transition_type.frm
general_log.CSV     innodb_index_stats.frm  slow_log.CSM       time_zone_transition_type.MYD
general_log.frm     innodb_index_stats.ibd  slow_log.CSV       time_zone_transition_type.MYI
gtid_slave_pos.frm  innodb_table_stats.frm  slow_log.frm       user.frm
gtid_slave_pos.ibd  innodb_table_stats.ibd  tables_priv.frm    user.MYD
help_category.frm   plugin.frm              tables_priv.MYD    user.MYI

同一个表有着不同的文件格式后缀,对应的是不同的数据库引擎

MYD——>MyISAM

查看服务器端数据库

# 服务器端的命令结束必须加分号;
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |# 比较特殊,该表格不是磁盘中的数据库,而是在内存中数据库
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)

指定访问数据库

# use 关键字命令可以不加分号;
MariaDB [(none)]> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> 

查看表格

MariaDB [mysql]> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| column_stats              |
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| gtid_slave_pos            |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| host                      |
| index_stats               |
| innodb_index_stats        |
| innodb_table_stats        |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| roles_mapping             |
| servers                   |
| slow_log                  |
| table_stats               |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
30 rows in set (0.00 sec)
# 这个数据库是mysql基于管理自身的表格

查看user表格

MariaDB [mysql]> desc user;
+------------------------+-----------------------------------+------+-----+----------+-------+
| Field                  | Type                              | Null | Key | Default  | Extra |
+------------------------+-----------------------------------+------+-----+----------+-------+
| Host                   | char(60)                          | NO   | PRI |          |       |
| User                   | char(80)                          | NO   | PRI |          |       |
| Password               | char(41)                          | NO   |     |          |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N        |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N        |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N        |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N        |       |
| File_priv              | enum('N','Y')                     | NO   |     | N        |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N        |       |
| References_priv        | enum('N','Y')                     | NO   |     | N        |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N        |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N        |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N        |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N        |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N        |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N        |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N        |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N        |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N        |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N        |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N        |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N        |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N        |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N        |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N        |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N        |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N        |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |          |       |
| ssl_cipher             | blob                              | NO   |     | NULL     |       |
| x509_issuer            | blob                              | NO   |     | NULL     |       |
| x509_subject           | blob                              | NO   |     | NULL     |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0        |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0        |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0        |       |
| max_user_connections   | int(11)                           | NO   |     | 0        |       |
| plugin                 | char(64)                          | NO   |     |          |       |
| authentication_string  | text                              | NO   |     | NULL     |       |
| password_expired       | enum('N','Y')                     | NO   |     | N        |       |
| is_role                | enum('N','Y')                     | NO   |     | N        |       |
| default_role           | char(80)                          | NO   |     |          |       |
| max_statement_time     | decimal(12,6)                     | NO   |     | 0.000000 |       |
+------------------------+-----------------------------------+------+-----+----------+-------+
46 rows in set (0.00 sec)


查看user、host、password三个字段

MariaDB [mysql]> select user,host,password from user;
+------+-----------------------+----------+
| user | host                  | password |
+------+-----------------------+----------+
| root | localhost             |          |
| root | localhost.localdomain |          |
| root | 127.0.0.1             |          |
| root | ::1                   |          |
|      | localhost             |          |
|      | localhost.localdomain |          |
+------+-----------------------+----------+
6 rows in set (0.00 sec)
# 投影运算:选择挑选字段的内容

有一些user为空,密码也为空,存在安全问题

user为空意思是可以随便填写用户名

安全加固/usr/bin/mysql_secure_installation

[root@localhost ~]# ll /usr/bin/mysql_secure_installation 
-rwxr-xr-x 1 root root 12527 May  8 20:36 /usr/bin/mysql_secure_installation
# 该文件是一个脚本
# 运行该脚本
[root@localhost ~]# mysql_secure_installation 

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] yes
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

运行网络远程登录

# mariadb要远程登录需要另外设置远程登录账户

MariaDB程序

  • 客户端程序:
    • mysql: 交互式的CLI工具
    • mysqldump:备份工具,基于mysql协议向mysqld发起查询请求,并将查得的所有数据转换成insert等写操作语句保存文本文件中
    • mysqladmin:基于mysql协议管理mysqld
    • mysqlimport:数据导入工具
  • MyISAM存储引擎的管理工具:
    • myisamchk:检查MyISAM库
    • myisampack:打包MyISAM表,只读
  • 服务器端程序
    • mysqld_safe
    • mysqld
    • mysqld_multi 多实例 ,示例:mysqld_multi --example

mysqladmin 说明

[root@localhost ~]# mysqladmin --help
mysqladmin  Ver 9.1 Distrib 10.2.32-MariaDB, for Linux on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Administration program for the mysqld daemon.
Usage: mysqladmin [OPTIONS] command command....

Default options are read from the following files in the given order:
/etc/my.cnf ~/.my.cnf 
The following groups are read: mysqladmin client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults          Print the program argument list and exit.
--no-defaults             Don't read default options from any option file.
The following specify which files/extra groups are read (specified before remaining options):
--defaults-file=#         Only read default options from the given file #.
--defaults-extra-file=#   Read this file after the global files are read.
--defaults-group-suffix=# Additionally read default groups with # appended as a suffix.

  -c, --count=#       Number of iterations to make. This works with -i
                      (--sleep) only.
  --debug-check       Check memory and open file usage at exit.
  --debug-info        Print some debug info at exit.
  -f, --force         Don't ask for confirmation on drop database; with
                      multiple commands, continue even if an error occurs.
  -C, --compress      Use compression in server/client protocol.
  --character-sets-dir=name 
                      Directory for character set files.
  --default-character-set=name 
                      Set the default character set.
  -?, --help          Display this help and exit.
  -h, --host=name     Connect to host.
  -l, --local         Local command, don't write to binlog.
  -b, --no-beep       Turn off beep on error.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -r, --relative      Show difference between current and previous values when
                      used with -i. Currently only works with extended-status.
  -s, --silent        Silently exit if one can't connect to server.
  -S, --socket=name   The socket file to use for connection.
  -i, --sleep=#       Execute commands repeatedly with a sleep between.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert 
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -u, --user=name     User for login if not current user.
  -v, --verbose       Write more information.
  -V, --version       Output version information and exit.
  -E, --vertical      Print output vertically. Is similar to --relative, but
                      prints output vertically.
  -w, --wait[=#]      Wait and retry if connection is down.
  --connect-timeout=# 
  --shutdown-timeout=# 
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
count                             0
debug-check                       FALSE
debug-info                        FALSE
force                             FALSE
compress                          FALSE
character-sets-dir                (No default value)
default-character-set             auto
host                              (No default value)
local                             FALSE
no-beep                           FALSE
port                              0
relative                          FALSE
socket                            (No default value)
sleep                             0
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
user                              (No default value)
verbose                           FALSE
vertical                          FALSE
connect-timeout                   43200
shutdown-timeout                  3600
plugin-dir                        (No default value)
default-auth                      (No default value)

Where command is a one or more of: (Commands may be shortened)
  create databasename	  Create a new database
  debug			  Instruct server to write debug information to log
  drop databasename	  Delete a database and all its tables
  extended-status         Gives an extended status message from the server
  flush-all-statistics    Flush all statistics tables
  flush-all-status        Flush status and statistics
  flush-client-statistics Flush client statistics
  flush-hosts             Flush all cached hosts
  flush-index-statistics  Flush index statistics
  flush-logs              Flush all logs
  flush-privileges        Reload grant tables (same as reload)
  flush-binary-log        Flush binary log
  flush-engine-log        Flush engine log(s)
  flush-error-log         Flush error log
  flush-general-log       Flush general log
  flush-relay-log         Flush relay log
  flush-slow-log          Flush slow query log
  flush-status            Clear status variables
  flush-table-statistics  Clear table statistics
  flush-tables            Flush all tables
  flush-threads           Flush the thread cache
  flush-user-statistics   Flush user statistics
  flush-user-resources    Flush user resources
  kill id,id,...	Kill mysql threads
  password [new-password] Change old password to new-password in current format
  old-password [new-password] Change old password to new-password in old format
  ping			Check if mysqld is alive
  processlist		Show list of active threads in server
  reload		Reload grant tables
  refresh		Flush all tables and close and open logfiles
  shutdown		Take server down
  status		Gives a short status message from the server
  start-slave		Start slave
  stop-slave		Stop slave
  variables             Prints variables available
  version		Get version info from server

检查数据库是否正常

[root@localhost ~]# mysqladmin -uroot -p ping
Enter password: 
mysqld is alive

关闭数据库

两种方法

systemctl stop mariadb
mysqladmin shutdown

注意:千万不要通过杀进程方式关闭服务器

更改口令密码

[root@localhost ~]# mysqladmin -uroot -proot password 
New password: 
Confirm new password: 
# 我将原本的口令改了

暴力破解口令

# 删除/var/lib/mysql/文件夹下所有内容
# 再重启mariadb服务
# mysql会恢复出始值

查看mariadb-server安装脚本

[root@localhost ~]# rpm -q --scripts MariaDB-server
preinstall scriptlet (using /bin/sh):
# Check if we can safely upgrade.  An upgrade is only safe if it's from one
# of our RPMs in the same version family.

installed=`rpm -q --whatprovides mysql-server 2> /dev/null`
if [ $? -eq 0 -a -n "$installed" ]; then
  installed=`echo "$installed"|sed -n 1p`
  vendor=`rpm -q --queryformat='%{VENDOR}' "$installed" 2>&1 | sed 's/Monty Program AB/MariaDB Foundation/'`
  version=`rpm -q --queryformat='%{VERSION}' "$installed" 2>&1`
  myvendor='MariaDB Foundation'
  myversion='10.2.32'

  old_family=`echo $version   | sed -n -e 's,^\([1-9][0-9]*\.[0-9][0-9]*\)\..*$,\1,p'`
  new_family=`echo $myversion | sed -n -e 's,^\([1-9][0-9]*\.[0-9][0-9]*\)\..*$,\1,p'`

  [ -z "$vendor" ] && vendor=''
  [ -z "$old_family" ] && old_family="$version>"
  [ -z "$new_family" ] && new_family="$myversion>"

  error_text=
  if [ "$vendor" != "$myvendor" ]; then
    error_text="$error_text
The current MariaDB server package is provided by a different
vendor ($vendor) than $myvendor.  Some files may be installed
to different locations, including log files and the service
startup script in /etc/init.d/.
"
  fi

  if [ "$old_family" != "$new_family" ]; then
    error_text="$error_text
Upgrading directly from MySQL $old_family to MariaDB $new_family may not
be safe in all cases.  A manual dump and restore using mysqldump is
recommended.  It is important to review the MariaDB manual's Upgrading
section for version-specific incompatibilities.
"
  fi

  if [ -n "$error_text" ]; then
    cat <<HERE >&2

******************************************************************
A MySQL or MariaDB server package ($installed) is installed.
$error_text
A manual upgrade is required.

- Ensure that you have a complete, working backup of your data and my.cnf
  files
- Shut down the MySQL server cleanly
- Remove the existing MySQL packages.  Usually this command will
  list the packages you should remove:
  rpm -qa | grep -i '^mysql-'

  You may choose to use 'rpm --nodeps -ev ' to remove
  the package which contains the mysqlclient shared library.  The
  library will be reinstalled by the MariaDB-shared package.
- Install the new MariaDB packages supplied by $myvendor
- Ensure that the MariaDB server is started
- Run the 'mysql_upgrade' program

This is a brief description of the upgrade process.  Important details
can be found in the MariaDB manual, in the Upgrading section.
******************************************************************
HERE
    exit 1
  fi
fi
postinstall scriptlet (using /bin/sh):

if [ -f /usr/lib/systemd/system/mariadb.service -a -x /usr/bin/systemctl ]; then
  systemd_conf=/etc/systemd/system/mariadb.service.d/migrated-from-my.cnf-settings.conf
  if [ -x /usr/bin/mariadb-service-convert -a ! -f "${systemd_conf}" ]; then
    # Either fresh install or upgrade non-systemd -> systemd
    mkdir -p /etc/systemd/system/mariadb.service.d
    /usr/bin/mariadb-service-convert > "${systemd_conf}"
    # Make sure old possibly non-systemd instance is down
    if [ $1 = 2 ]; then
      SYSTEMCTL_SKIP_REDIRECT=1 /etc/init.d/mysql stop >/dev/null 2>&1 || :
      systemctl start mariadb >/dev/null 2>&1 || :
    fi
    systemctl enable mariadb.service >/dev/null 2>&1 || :
  fi
fi

# Make MySQL start/shutdown automatically when the machine does it.
if [ $1 = 1 ] ; then
  if [ -x /usr/bin/systemctl ] ; then
          /usr/bin/systemctl daemon-reload >/dev/null 2>&1 || :
          /usr/bin/systemctl preset mariadb.service >/dev/null 2>&1 || :
  elif [ -x /sbin/chkconfig ] ; then
          /sbin/chkconfig --add mysql
  fi

  basedir=`/usr/bin/my_print_defaults --mysqld|sed -ne 's/^--basedir=//p'|tail -1`
  if [ -z "$basedir" ] ; then
    basedir=/usr
  fi

  datadir=`/usr/bin/my_print_defaults --mysqld|sed -ne 's/^--datadir=//p'|tail -1`
  if [ -z "$datadir" ] ; then
    datadir=/var/lib/mysql
  else
    # datadir may be relative to a basedir!
    if ! expr $datadir : / > /dev/null; then
      datadir=$basedir/$datadir
    fi
  fi

  # Create a MySQL user and group. Do not report any problems if it already
  # exists.
  groupadd -r mysql 2> /dev/null || true
  useradd -M -r --home $datadir --shell /sbin/nologin --comment "MySQL server" --gid mysql mysql 2> /dev/null || true 
  # The user may already exist, make sure it has the proper group nevertheless (BUG#12823)
  usermod --gid mysql mysql 2> /dev/null || true

  # Temporary Workaround for MDEV-11386 - will be corrected in Advance Toolchain 10.0-3 and 8.0-8
  for ldconfig in /opt/at*/sbin/ldconfig; do
     test -x $ldconfig && $ldconfig
  done

  # Change permissions so that the user that will run the MySQL daemon
  # owns all database files.
  chown -R -f mysql:mysql $datadir

  if [ ! -e $datadir/mysql ]; then
    # Create data directory
    mkdir -p $datadir

    # Initiate databases
    /usr/bin/mysql_install_db --rpm --user=mysql
  fi

  # Change permissions again to fix any new files.
  chown -R mysql:mysql $datadir

  # Fix permissions for the permission database so that only the user
  # can read them.
  chmod -R og-rw $datadir/mysql
fi

# install SELinux files - but don't override existing ones
SETARGETDIR=/etc/selinux/targeted/src/policy
SEDOMPROG=$SETARGETDIR/domains/program
SECONPROG=$SETARGETDIR/file_contexts/program

if [ -x /usr/sbin/semodule ] ; then
  /usr/sbin/semodule -i /usr/share/mysql/policy/selinux/mariadb.pp
fi

if [ -x sbin/restorecon ] ; then
	sbin/restorecon -R var/lib/mysql
fi
preuninstall scriptlet (using /bin/sh):

if [ $1 = 0 ] ; then
        # Stop MySQL before uninstalling it
        # Don't start it automatically anymore
        if [ -x /usr/bin/systemctl ] ; then
                /usr/bin/systemctl stop mariadb.service > /dev/null 2>&1
                /usr/bin/systemctl disable mariadb.service > /dev/null 2>&1
        fi
        if [ -x /etc/init.d/mysql ] ; then
                /etc/init.d/mysql stop > /dev/null
        fi
        if [ -x /sbin/chkconfig ] ; then
                /sbin/chkconfig --del mysql > /dev/null 2>&1 || :
        fi
fi

# We do not remove the mysql user since it may still own a lot of
# database files.
postuninstall scriptlet (using /bin/sh):
if [ $1 -ge 1 ]; then
  # request the server restart
  mkdir -p /var/lib/rpm-state/mariadb
  echo > /var/lib/rpm-state/mariadb/need-restart
fi

if [ $1 = 0 ] ; then
  if [ -x /usr/bin/systemctl ] ; then
    /usr/bin/systemctl daemon-reload > /dev/null 2>&1
  fi
fi
posttrans scriptlet (using /bin/sh):
if [ -r /var/lib/rpm-state/mariadb/need-restart ] ; then
  rm /var/lib/rpm-state/mariadb/need-restart
  if [ -x /usr/bin/systemctl ] ; then
    /usr/bin/systemctl daemon-reload > /dev/null 2>&1
    /usr/bin/systemctl try-restart mariadb.service > /dev/null 2>&1
  elif /etc/init.d/mysql status > /dev/null 2>&1; then
    # only restart the server if it was alredy running
    /etc/init.d/mysql restart
  fi
fi

用户账号

  • mysql用户账号由两部分组成:
    • ‘USERNAME’@'HOST‘
  • 说明:
    HOST限制此用户可通过哪些远程主机连接mysql服务器
    支持使用通配符:
    • % 匹配任意长度的任意字符
    • 172.16.0.0/255.255.0.0 或 172.16.%.%
    • _ 匹配任意单个字符

mysql的配置文件

[root@localhost ~]# cat /etc/my.cnf
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

#
# include *.cnf from the config directory
#
!includedir /etc/my.cnf.d
#也可以放入 /etc/my.cnf.d文件夹下
[root@localhost ~]# tree /etc/my.cnf.d
/etc/my.cnf.d
├── enable_encryption.preset
├── mysql-clients.cnf
└── server.cnf

0 directories, 3 files

查看mysql-clients.cnf

[root@localhost ~]# cat /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]

[mysql_upgrade]

[mysqladmin]

[mysqlbinlog]

[mysqlcheck]

[mysqldump]

[mysqlimport]

[mysqlshow]

[mysqlslap]

维护数据库时,关闭3306端口,仅仅本地连接

vim /etc/my.cnf
[mysqld]
skip-networking=1
#关闭网络连接,只侦听本地客户端, 所有和服务器的交互都通过一个socket实现,socket的配置存放在/var/lib/mysql/mysql.sock) 可在/etc/my.cnf修改

mysql客户端可用选项:

  • -A, --no-auto-rehash 禁止补全
  • -u, --user= 用户名,默认为root
  • -h, --host= 服务器主机,默认为localhost
  • -p, --passowrd= 用户密码,建议使用-p,默认为空密码
  • -P, --port= 服务器端口
  • -S, --socket= 指定连接socket文件路径
  • -D, --database= 指定默认数据库
  • -C, --compress 启用压缩
  • -e “SQL“ 执行SQL命令
  • -V, --version 显示版本
  • -v --verbose 显示详细信息
  • –print-defaults 获取程序默认使用的配置

socket地址

  • 服务器监听的两种socket地址:
    • ip socket: 监听在tcp的3306端口,支持远程通信
    • unix sock: 监听在sock文件上,仅支持本机通信
      如:/var/lib/mysql/mysql.sock)
    • 说明:host为localhost,127.0.0.1时自动使用unix sock

显示当前数据库版本号

MariaDB [(none)]> select version();
+-----------------+
| version()       |
+-----------------+
| 10.2.32-MariaDB |
+-----------------+
1 row in set (0.00 sec)

二进制安装(区别源码编译)

二进制格式安装过程

  • (1) 准备用户
groupadd -r -g 306 mysql
useradd -r -g 306 -u 306 –d /data/mysql mysql
  • (2) 准备数据目录,建议使用逻辑卷
mkdir /data/mysql
chown mysql:mysql /data/mysql
  • (3) 准备二进制程序
tar xf mariadb-VERSION-linux-x86_64.tar.gz -C /usr/local	# 解压缩必须指定该位置
cd /usr/local
ln -sv mariadb-VERSION mysql
chown -R root:mysql /usr/local/mysql/
  • (4) 准备配置文件
mkdir /etc/mysql/
cp support-files/my-large.cnf /etc/mysql/my.cnf
#[mysqld]中添加三个选项:
datadir = /data/mysql
innodb_file_per_table = on
skip_name_resolve = on #禁止主机名解析,建议使用
  • (5)创建数据库文件
cd /usr/local/mysql/
./scripts/mysql_install_db --datadir=/data/mysql --user=mysql
  • (6)准备服务脚本,并启动服务
cp ./support-files/mysql.server /etc/rc.d/init.d/mysqld
chkconfig --add mysqld
service mysqld start
# centos 6 的用法
  • (7)PATH路径
echo ‘PATH=/user/local/mysql/bin:$PATH> /etc/profile.d/mysql
  • (8)安全初始化
/user/local/mysql/bin/mysql_secure_installation

实验

目标:将数据安装在/data/mysql文件中

创建目录

[root@localhost ~]# mkdir -p /data/mysql/
[root@localhost ~]# useradd -r -s /sbin/nologin -d /data/mysql/ mysql

# 不加-m强制生成家目录的选项,因为这个选项会在目录下生成一下.bash开头的文件,不符合我们的要求

解压缩二进制文件

tar xf mariadb-VERSION-linux-x86_64.tar.gz -C /usr/local

[root@localhost ~]# cd /usr/local/
[root@localhost /usr/local]# ls
bin  games    lib    libexec                       sbin   src
etc  include  lib64  mariadb-10.2.25-linux-x86_64  share
[root@localhost /usr/local]# ln -s mariadb-10.2.25-linux-x86_64/ mysql

[root@localhost /usr/local]# ll
lrwxrwxrwx   1 root root  29 Jun 25 17:42 mysql -> mariadb-10.2.25-linux-x86_64/

[root@localhost /usr/local]# ll mysql/
total 176
drwxr-xr-x  2 1021 1004  4096 Mar 15  2019 bin
-rw-r--r--  1 1021 1004 17987 Jun 15  2019 COPYING
-rw-r--r--  1 1021 1004  2354 Jun 15  2019 CREDITS
drwxrwxr-x  3 1021 1004    18 Jun 15  2019 data
-rw-r--r--  1 1021 1004  8245 Jun 15  2019 EXCEPTIONS-CLIENT
drwxrwxr-x  3 1021 1004    19 Jun 15  2019 include
-rw-r--r--  1 1021 1004  8694 Jun 15  2019 INSTALL-BINARY
drwxr-xr-x  5 1021 1004   335 Mar 15  2019 lib
drwxrwxr-x  4 1021 1004    30 Jun 15  2019 man
drwxrwxr-x 11 1021 1004  4096 Jun 15  2019 mysql-test
-rw-r--r--  1 1021 1004  2843 Jun 15  2019 README.md
-rw-r--r--  1 1021 1004 19477 Jun 15  2019 README-wsrep
drwxrwxr-x  2 1021 1004    30 Jun 15  2019 scripts
drwxrwxr-x 32 1021 1004  4096 Jun 15  2019 share
drwxrwxr-x  4 1021 1004  4096 Jun 15  2019 sql-bench
drwxrwxr-x  3 1021 1004   275 Jun 15  2019 support-files
-rw-r--r--  1 1021 1004 86263 Jun 15  2019 THIRDPARTY
# 发现mysql下的文件所属主与组都有问题,因此需要统一修改

[root@localhost /usr/local]# chown -R root.root mysql/

[root@localhost /usr/local]# ll mysql/
total 176
drwxr-xr-x  2 root root  4096 Mar 15  2019 bin
-rw-r--r--  1 root root 17987 Jun 15  2019 COPYING
-rw-r--r--  1 root root  2354 Jun 15  2019 CREDITS
drwxrwxr-x  3 root root    18 Jun 15  2019 data
-rw-r--r--  1 root root  8245 Jun 15  2019 EXCEPTIONS-CLIENT
drwxrwxr-x  3 root root    19 Jun 15  2019 include
-rw-r--r--  1 root root  8694 Jun 15  2019 INSTALL-BINARY
drwxr-xr-x  5 root root   335 Mar 15  2019 lib
drwxrwxr-x  4 root root    30 Jun 15  2019 man
drwxrwxr-x 11 root root  4096 Jun 15  2019 mysql-test
-rw-r--r--  1 root root  2843 Jun 15  2019 README.md
-rw-r--r--  1 root root 19477 Jun 15  2019 README-wsrep
drwxrwxr-x  2 root root    30 Jun 15  2019 scripts
drwxrwxr-x 32 root root  4096 Jun 15  2019 share
drwxrwxr-x  4 root root  4096 Jun 15  2019 sql-bench
drwxrwxr-x  3 root root   275 Jun 15  2019 support-files
-rw-r--r--  1 root root 86263 Jun 15  2019 THIRDPARTY

初始化脚本

[root@localhost /usr/local/mysql]# ls scripts/
mysql_install_db

源码编译

步骤

安装包

yum install bison bison-devel zlib-devel libcurl-devel libarchive-devel boost-devel gcc gcc-c++ cmake ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel -y

如果编译过程出错,尝试安装此包

yum install libdb-cxx-devel

做准备用户和数据目录

useradd –r –s /sbin/nologin –d /data/mysql/ mysql
mkdir /data/mysql
chown mysql.mysql /data/mysql
tar xvf mariadb-10.2.18.tar.gz

cmake 编译安装

cmake的重要特性之一是其独立于源码(out-of-source)的编译功能,即编译工作可以在另一个指定的目录中而非源码目录中进行,这可以保证源码目录不受任何一次编译的影响,因此在同一个源码树上可以进行多次不同的编译,如针对于不同平台编译
编译选项:https://dev.mysql.com/doc/refman/5.7/en/source-configuration-options.html

cd mariadb-10.2.18/
###################################
cmake . \
-DCMAKE_INSTALL_PREFIX=/app/mysql \
-DMYSQL_DATADIR=/data/mysql/ \
-DSYSCONFDIR=/etc/mysql \
-DMYSQL_USER=mysql \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITHOUT_MROONGA_STORAGE_ENGINE=1 \
-DWITH_DEBUG=0 \
-DWITH_READLINE=1 \
-DWITH_SSL=system \
-DWITH_ZLIB=system \
-DWITH_LIBWRAP=0 \
-DENABLED_LOCAL_INFILE=1 \
-DMYSQL_UNIX_ADDR=/data/mysql/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci

###########################################
make && make install

提示:如果出错,执行rm -f CMakeCache.txt

准备环境变量

echo 'PATH=/app/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
. /etc/profile.d/mysql.sh

生成数据库文件

cd /app/mysql/
scripts/mysql_install_db --datadir=/data/mysql/ --user=mysql

准备配置文件

cp /app/mysql/support-files/my-huge.cnf /etc/my.cnf

准备启动脚本

cp /app/mysql/support-files/mysql.server /etc/init.d/mysqld

启动服务

chkconfig --add mysqld ;service mysqld start

多实例

要求在有限的机器上,跑多个服务器,且彼此独立互不影响

在实验主机上跑3个数据库且端口独立

步骤

/mysql/{3306,3307,3308}分别实例3个独立的数据库,并建立相应文件目录

[root@localhost ~]# mkdir -pv  /mysql/{3306,3307,3308}/{data,bin,log,socket,pid,etc}

[root@localhost ~]# tree /mysql/
/mysql/
├── 3306
│   ├── bin
│   ├── data
│   ├── etc
│   ├── log
│   ├── pid
│   └── socket
├── 3307
│   ├── bin
│   ├── data
│   ├── etc
│   ├── log
│   ├── pid
│   └── socket
└── 3308
    ├── bin
    ├── data
    ├── etc
    ├── log
    ├── pid
    └── socket

更改/mysql下的所有所属组和所属主

chown -R mysql.mysql /mysql/

实验前注意关闭已经开启的 mariadb服务

运行mysql的安装脚本mysql_install_db

mysql_install_db --datadir=/mysql/{3306,3307,3308}/data/ --user=mysql

建立配置文件

cp /etc/my.cnf /mysql/3306/etc/
vim /mysql/3306/etc/my.cnf

############################

[mysqld]
port=3306
datadir=/mysql/3306/data/
socket=/mysql/3306/socket/mysql.sock

symbolic-links=0


[mysqld_safe]
log-error=/mysql/3306/log/mariadb.log
pid-file=/mysql/3306/pid/mariadb.pid

                                         

将配置文件修改好后,复制到3307,3308对应文件夹下,并改好端口

cp /mysql/3306/etc/my.cnf /mysql/3307/etc/
cp /mysql/3306/etc/my.cnf /mysql/3308/etc/

############################################
sed -i 's/3306/3307/' /mysql/3307/etc/my.cnf
sed -i 's/3306/3308/' /mysql/3308/etc/my.cnf 

启动脚本

[root@localhost bin]# pwd
/mysql/3306/bin

[root@localhost bin]# cat mysqld 
#!/bin/bash

port=3306
mysql_user="root"
mysql_pwd=""
cmd_path="/usr/bin"
mysql_basedir="/mysql"
mysql_sock="${mysql_basedir}/${port}/socket/mysql.sock"

function_start_mysql()
{
    if [ ! -e "$mysql_sock" ];then
      printf "Are you OK? Starting MySQL...\n"
      ${cmd_path}/mysqld_safe --defaults-file=${mysql_basedir}/${port}/etc/my.cnf  &> /dev/null  &
    else
      printf "Are you OK? MySQL is running...\n"
      exit
    fi
}


function_stop_mysql()
{
    if [ ! -e "$mysql_sock" ];then
       printf "Are you OK? MySQL is stopped...\n"
       exit
    else
       printf "Are you OK? Stoping MySQL...\n"
       ${cmd_path}/mysqladmin -u ${mysql_user} -p${mysql_pwd} -S ${mysql_sock} shutdown
   fi
}


function_restart_mysql()
{
    printf "Are you OK? Restarting MySQL...\n"
    function_stop_mysql
    sleep 2
    function_start_mysql
}

case $1 in
start)
    function_start_mysql
;;
stop)
    function_stop_mysql
;;
restart)
    function_restart_mysql
;;
*)
    printf "Usage: ${mysql_basedir}/${port}/bin/mysqld {start|stop|restart}\n"
esac


cp mysqld /mysql/3307/bin/
cp mysqld /mysql/3308/bin/

##########################

sed -i 's/3306/3307/' /mysql/3307/bin/mysqld 
sed -i 's/3306/3308/' /mysql/3308/bin/mysqld 

启动服务

[root@localhost bin]# /mysql/3306/bin/mysqld start
Are you OK? Starting MySQL...
[root@localhost bin]# /mysql/3307/bin/mysqld start
Are you OK? Starting MySQL...
[root@localhost bin]# /mysql/3308/bin/mysqld start
Are you OK? Starting MySQL...

##################################################
[root@localhost bin]# ss -ntl
State      Recv-Q Send-Q   Local Address:Port                  Peer Address:Port              
LISTEN     0      100          127.0.0.1:25                               *:*                  
LISTEN     0      128                  *:22                               *:*                  
LISTEN     0      100              [::1]:25                            [::]:*                  
LISTEN     0      80                [::]:3306                          [::]:*                  
LISTEN     0      80                [::]:3307                          [::]:*                  
LISTEN     0      80                [::]:3308                          [::]:*                  
LISTEN     0      128               [::]:22                            [::]:* 

测试连接3307

[root@localhost bin]# mysql -S /mysql/3307/socket/mysql.sock 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.2.32-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)]> status
--------------
mysql  Ver 15.1 Distrib 10.2.32-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:		8
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		10.2.32-MariaDB MariaDB Server
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
UNIX socket:		/mysql/3307/socket/mysql.sock
Uptime:			1 min 36 sec

Threads: 7  Questions: 4  Slow queries: 0  Opens: 17  Flush tables: 1  Open tables: 11  Queries per second avg: 0.041
--------------

设置口令

mysqladmin -S /mysql/3308/socket/mysql.sock password centos

SQL语句

数据库:database
表:table
	行:row
	列:column
索引:index
视图:view
用户:user
权限:privilege
存储过程:procedure
存储函数:function
触发器:trigger
事件调度器:event scheduler,任务计划

SQL语句分类:

  • DDL: Data Defination Language 数据定义语言
    • CREATE,DROP,ALTER
  • DML: Data Manipulation Language 数据操纵语言
    • INSERT,DELETE,UPDATE
  • DCL:Data Control Language 数据控制语言
    • GRANT,REVOKE,COMMIT,ROLLBACK
  • DQL:Data Query Language 数据查询语言
    • SELECT

SQL语句关键字建议大写

创建数据库

CREATE DATABASE|SCHEMA [IF NOT EXISTS] 'DB_NAME';
CHARACTER SET 'character set name’COLLATE 'collate name'

修改数据库

ALTER DATABASE DB_NAME character set utf8;

删除数据库

DROP DATABASE|SCHEMA [IF EXISTS] 'DB_NAME';

查看支持所有字符集

SHOW CHARACTER SET;

查看支持所有排序规则

SHOW COLLATION;

获取命令使用帮助

mysql> HELP KEYWORD;

查看数据库列表

mysql> SHOW DATABASES;

数据类型

MySql支持多种列类型:

  • 数值类型
  • 日期/时间类型
  • 字符串(字符)类型
  • https://dev.mysql.com/doc/refman/5.5/en/data-types.html
  • 选择正确的数据类型对于获得高性能至关重要,三大原则:
    • 更小的通常更好,尽量使用可正确存储数据的最小数据类型
    • 简单就好,简单数据类型的操作通常需要更少的CPU周期
    • 尽量避免NULL,包含为NULL的列,对MySQL更难优化

整型

  • 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值视为真

浮点型(float和double),近似值

  • float(m,d) 单精度浮点型 8位精度(4字节) m总个数,d小数位
  • double(m,d) 双精度浮点型16位精度(8字节) m总个数,d小数位
  • 设一个字段定义为float(6,3),如果插入一个数123.45678,实际数据库里存的是123.457,但总个数还以实际为准,即6位

定点数

  • 在数据库中存放的是精确值,存为十进制
  • decimal(m,d) 参数m<65 是总个数,d<30且 d
  • MySQL5.0和更高版本将数字打包保存到一个二进制字符串中(每4个字节存9个数字)。例如,decimal(18,9)小数点两边将各存储9个数字,一共使用9个字节:小数点前的数字用4个字节,小数点后的数字用4个字节,小数点本身占1个字节
  • 浮点类型在存储同样范围的值时,通常比decimal使用更少的空间。float使用4个字节存储。double占用8个字节
  • 因为需要额外的空间和计算开销,所以应该尽量只在对小数进行精确计算时才使用decimal——例如存储财务数据。但在数据量比较大的时候,可以考虑使用bigint代替decimal

字符串(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

  • char(n) 若存入字符数小于n,则以空格补于其后,查询之时再将空格去掉,所以char类型存储的字符串末尾不能有空格,varchar不限于此
  • char(n) 固定长度,char(4)不管是存入几个字符,都将占用4个字节,varchar是存入的实际字符数+1个字节(n< n>255),所以varchar(4),存入3个字符将占用4个字节
  • char类型的字符串检索速度要比varchar类型的快

varchar和text

  • varchar可指定n,text不能指定,内部存储varchar是存入的实际字符数+1个字节(n< n>255),text是实际字符数+2个字节。
  • text类型不能有默认值
  • varchar可直接创建索引,text创建索引要指定前多少个字符。varchar查询速度快于text

二进制数据:BLOB

  • BLOB和text存储方式不同,TEXT以文本方式存储,英文存储区分大小写,而Blob是以二进制方式存储,不分大小写
  • BLOB存储的数据只能整体读出
  • TEXT可以指定字符集,BLOB不用指定字符集

日期时间类型

  • date 日期 ‘2008-12-2’
  • time 时间 ‘12:25:36’
  • datetime 日期时间 ‘2008-12-2 22:06:44’
  • timestamp 自动存储记录修改时
  • YEAR(2), YEAR(4):年份
  • timestamp字段里的时间数据会随其他字段修改的时候自动刷新,这个数据类型的字段可以存放这条记录最后被修改的时间

修饰符

所有类型

  • NULL 数据列可包含NULL值
  • NOT NULL 数据列不允许包含NULL值
  • DEFAULT 默认值
  • PRIMARY KEY 主键
  • UNIQUE KEY 唯一键
  • CHARACTER SET name 指定一个字符集

数值型

  • AUTO_INCREMENT 自动递增,适用于整数类型
  • UNSIGNED 无符号

示例:

CREATE TABLE students (id int UNSIGNED NOT NULL PRIMARY KEY,name VARCHAR(20)NOT NULL,age tinyint UNSIGNED);

DESC students;

CREATE TABLE students2 (id int UNSIGNED NOT NULL ,name VARCHAR(20) NOT NULL,age tinyint UNSIGNED,PRIMARY KEY(id,name));

DML语言

DML: INSERT, DELETE, UPDATE

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 tbl_name [(col1,...)] VALUES (val1,...), (val21,...)


##################


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 INTO students VALUES(1,'tom','m'),(2,'alice','f');
INSERT INTO students(id,name) VALUES(3,'jack'),(4,'allen');

UPDATE

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

注意:这种操作非常危险,且不能恢复,最好执行的是safe update模式

Mysql 选项:-U|–safe-updates| --i-am-a-dummy

将sefe-updates写入Mysql客户端配置文件中

DELETE(清空表,表还在,数据没了)


TRUNCATE TABLE tbl_name; 快速清空表

mysql客户端默认字符集

mariadb服务器端字符集

查看表格的字符集信息

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)

SQL语句DQL单表查询

SELECT

从入门到删库跑路的过程_第2张图片

MariaDB [hellodb]> help select;
Name: 'SELECT'
Description:
Syntax:
SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    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}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

SELECT的小功能

MariaDB [hellodb]> select "hello";
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)

# echo 功能
MariaDB [hellodb]> select 200*30;
+--------+
| 200*30 |
+--------+
|   6000 |
+--------+
1 row in set (0.00 sec)

# 数字运算

数据库导入

[root@localhost ~]# mysql < hellodb_innodb.sql

查看表内容

MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
7 rows in set (0.00 sec)

查看students表内容

MariaDB [hellodb]> SELECT * FROM students;
+-------+---------------+-----+--------+---------+-----------+
| 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 |
|    10 | Yue Lingshan  |  19 | F      |       3 |      NULL |
|    11 | Yuan Chengzhi |  23 | M      |       6 |      NULL |
|    12 | Wen Qingqing  |  19 | F      |       1 |      NULL |
|    13 | Tian Boguang  |  33 | M      |       2 |      NULL |
|    14 | Lu Wushuang   |  17 | F      |       3 |      NULL |
|    15 | Duan Yu       |  19 | M      |       4 |      NULL |
|    16 | Xu Zhu        |  21 | M      |       1 |      NULL |
|    17 | Lin Chong     |  25 | M      |       4 |      NULL |
|    18 | Hua Rong      |  23 | M      |       7 |      NULL |
|    19 | Xue Baochai   |  18 | F      |       6 |      NULL |
|    20 | Diao Chan     |  19 | F      |       7 |      NULL |
|    21 | Huang Yueying |  22 | F      |       6 |      NULL |
|    22 | Xiao Qiao     |  20 | F      |       1 |      NULL |
|    23 | Ma Chao       |  23 | M      |       4 |      NULL |
|    24 | Xu Xian       |  27 | M      |    NULL |      NULL |
|    25 | Sun Dasheng   | 100 | M      |    NULL |      NULL |
+-------+---------------+-----+--------+---------+-----------+
25 rows in set (0.00 sec)

将选择的标题改成中文

# 别名可以加as也可以不加
MariaDB [hellodb]> SELECT NAME as 姓名,AGE 年龄,stuid FROM students;
+---------------+--------+-------+
| 姓名          | 年龄   | stuid |
+---------------+--------+-------+
| Shi Zhongyu   |     22 |     1 |
| Shi Potian    |     22 |     2 |
| Xie Yanke     |     53 |     3 |
| Ding Dian     |     32 |     4 |
| Yu Yutong     |     26 |     5 |
| Shi Qing      |     46 |     6 |
| Xi Ren        |     19 |     7 |
| Lin Daiyu     |     17 |     8 |
| Ren Yingying  |     20 |     9 |
| Yue Lingshan  |     19 |    10 |
| Yuan Chengzhi |     23 |    11 |
| Wen Qingqing  |     19 |    12 |
| Tian Boguang  |     33 |    13 |
| Lu Wushuang   |     17 |    14 |
| Duan Yu       |     19 |    15 |
| Xu Zhu        |     21 |    16 |
| Lin Chong     |     25 |    17 |
| Hua Rong      |     23 |    18 |
| Xue Baochai   |     18 |    19 |
| Diao Chan     |     19 |    20 |
| Huang Yueying |     22 |    21 |
| Xiao Qiao     |     20 |    22 |
| Ma Chao       |     23 |    23 |
| Xu Xian       |     27 |    24 |
| Sun Dasheng   |    100 |    25 |
+---------------+--------+-------+
25 rows in set (0.00 sec)

WHERE子句:指明过滤条件以实现“选择”的功能:

过滤条件:布尔型表达式
算术操作符:+, -, *, /, %
比较操作符:=,<=>(相等或都为空), <>, !=(非标准SQL), >, >=, <, <=
BETWEEN min_num AND max_num
IN (element1, element2, …)
IS NULL
IS NOT NULL

对特定行的操作WHERE


SQL注入

SELECT * FROM user WHERE usename='admin' and password='' or '1'='1';
SELECT * FROM user WHERE username='admin'--' and password=''';

DISTINCT 去除重复列

SELECT DISTINCT gender FROM students;

LIKE:
% 任意长度的任意字符
_ 任意单个字符

RLIKE:正则表达式,索引失效,不建议使用
REGEXP:匹配字符串可用正则表达式书写模式,同上

逻辑操作符:

NOT
AND
OR
XOR

GROUP:根据指定的条件把查询结果进行“分组”以用于做“聚合”运算

avg(), max(), min(), count(), sum()

HAVING: 对分组聚合运算后的结果指定过滤条件
ORDER BY: 根据指定的字段对查询结果进行排序

升序:ASC
降序:DESC

LIMIT [[offset,]row_count]:对查询的结果进行输出行数数量限制
对查询结果中的数据请求施加“锁”

FOR UPDATE: 写锁,独占或排它锁,只有一个读和写
LOCK IN SHARE MODE: 读锁,共享锁,同时多个读

检测某列是否为空

SELECT * FROM students WHERE classid IS null;

检测非空

SELECT * FROM students WHERE classid IS NOT null;

聚合函数

SELECT COUNT(ClassID) AS 记录行数 FROM students;
/*返回非空的列对应的所有数量*/

如果要统计共有多少行,则直接选择主键,因为主键不能为空

MAX()

MIN()

平均年龄

MariaDB [hellodb]> SELECT AVG(age) AS 平均年龄 FROM students; 
+--------------+
| 平均年龄      |
+--------------+
|      27.4000 |
+--------------+

分组统计GROUP BY

SELECT ClassID , AVG(age) AS 平均年龄 FROM students GROUP BY ClassID; 

一旦做了分组,SELECT 后的字段名必须是分组名与聚合函数

HAVING

分组之后再过滤

SELECT ClassID , AVG(age) AS 平均年龄 FROM students GROUP BY ClassID HAVING AVG(age) > 30; 

注意:使用HAVING是在分组之后,而WHERE是在分组之前

加别名的写法

SELECT ClassID , AVG(age) AS avg FROM students GROUP BY ClassID HAVING avg > 30; 

SELECT ClassID , AVG(age) AS 平均年龄 FROM students GROUP BY ClassID HAVING 平均年龄 > 30;

多次分组

MariaDB [hellodb]> SELECT classid,gender,AVG(age) FROM students GROUP BY classid,gender;
+---------+--------+----------+
| classid | gender | AVG(age) |
+---------+--------+----------+
|    NULL | M      |  63.5000 |
|       1 | F      |  19.5000 |
|       1 | M      |  21.5000 |
|       2 | M      |  36.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 |
+---------+--------+----------+
12 rows in set (0.00 sec)

排序ORDER BY

默认是正序排

SELECT * FROM students ORDER BY age;

倒序排加DESC

SELECT * FROM students ORDER BY age DESC;

排除NULL至最后,只针对数字型有效 :在搜索字段前加 -

SELECT * FROM students ORDER BY -classid DESC;

ORDER BY 与 GROUP BY的综合应用

按班级排序,显示每个班级年龄的总和

MariaDB [hellodb]> SELECT ClassID,SUM(age) AS age FROM students GROUP BY ClassID  ORDER BY -classid DESC;
+---------+------+
| ClassID | age  |
+---------+------+
|       1 |   82 |
|       2 |  108 |
|       3 |   81 |
|       4 |   99 |
|       5 |   46 |
|       6 |   83 |
|       7 |   59 |
|    NULL |  127 |
+---------+------+
8 rows in set (0.00 sec)

排除NULL值

MariaDB [hellodb]> SELECT ClassID,SUM(age) AS age FROM students GROUP BY ClassID HAVING classid IS NOT NULL  ORDER BY -classid DESC;
+---------+------+
| ClassID | age  |
+---------+------+
|       1 |   82 |
|       2 |  108 |
|       3 |   81 |
|       4 |   99 |
|       5 |   46 |
|       6 |   83 |
|       7 |   59 |
+---------+------+
7 rows in set (0.00 sec)

HAVING 关键字应当跟在GROUP BY之后

或者直接

MariaDB [hellodb]> SELECT ClassID,SUM(age) AS age FROM students WHERE ClassID IS NOT NULL  GROUP BY ClassID ORDER BY -classid DESC;
+---------+------+
| ClassID | age  |
+---------+------+
|       1 |   82 |
|       2 |  108 |
|       3 |   81 |
|       4 |   99 |
|       5 |   46 |
|       6 |   83 |
|       7 |   59 |
+---------+------+
7 rows in set (0.00 sec)

LIMIT

显示前几行数据

MariaDB [hellodb]> SELECT ClassID,SUM(age) AS age FROM students WHERE ClassID IS NOT NULL  GROUP BY ClassID ORDER BY -classid DESC LIMIT 3;
+---------+------+
| ClassID | age  |
+---------+------+
|       1 |   82 |
|       2 |  108 |
|       3 |   81 |
+---------+------+
3 rows in set (0.00 sec)

跳过前两行,取后续的3行

MariaDB [hellodb]> SELECT ClassID,SUM(age) AS age FROM students WHERE ClassID IS NOT NULL  GROUP BY ClassID ORDER BY -classid DESC LIMIT 2,3;
+---------+------+
| ClassID | age  |
+---------+------+
|       3 |   81 |
|       4 |   99 |
|       5 |   46 |
+---------+------+
3 rows in set (0.00 sec)

选择查看相应的ClassID信息

MariaDB [hellodb]> SELECT * FROM students WHERE ClassID in (1,3,5);
+-------+--------------+-----+--------+---------+-----------+
| StuID | Name         | Age | Gender | ClassID | TeacherID |
+-------+--------------+-----+--------+---------+-----------+
|     2 | Shi Potian   |  22 | M      |       1 |         7 |
|     5 | Yu Yutong    |  26 | M      |       3 |         1 |
|     6 | Shi Qing     |  46 | M      |       5 |      NULL |
|     7 | Xi Ren       |  19 | F      |       3 |      NULL |
|    10 | Yue Lingshan |  19 | F      |       3 |      NULL |
|    12 | Wen Qingqing |  19 | F      |       1 |      NULL |
|    14 | Lu Wushuang  |  17 | F      |       3 |      NULL |
|    16 | Xu Zhu       |  21 | M      |       1 |      NULL |
|    22 | Xiao Qiao    |  20 | F      |       1 |      NULL |
+-------+--------------+-----+--------+---------+-----------+
9 rows in set (0.00 sec)


练习

导入hellodb.sql生成数据库

[root@localhost ~]# mysql < hellodb_innodb.sql

(1) 在students表中,查询年龄大于25岁,且为男性的同学的名字和年龄

SELECT name,age FROM students WHERE age > 25 and Gender = 'M';

(2) 以ClassID为分组依据,显示每组的平均年龄

MariaDB [hellodb]> SELECT ClassID , AVG(age) AS 平均年龄 FROM students GROUP BY ClassID; 
+---------+--------------+
| ClassID | 平均年龄     |
+---------+--------------+
|    NULL |      63.5000 |
|       1 |      20.5000 |
|       2 |      36.0000 |
|       3 |      20.2500 |
|       4 |      24.7500 |
|       5 |      46.0000 |
|       6 |      20.7500 |
|       7 |      19.6667 |
+---------+--------------+
8 rows in set (0.00 sec)

(3) 显示第2题中平均年龄大于30的分组及平均年龄

MariaDB [hellodb]> SELECT ClassID , AVG(age) AS 平均年龄 FROM students GROUP BY ClassID HAVING AVG(age) > 30; 
+---------+--------------+
| ClassID | 平均年龄     |
+---------+--------------+
|    NULL |      63.5000 |
|       2 |      36.0000 |
|       5 |      46.0000 |
+---------+--------------+
3 rows in set (0.00 sec)

(4) 显示以L开头的名字的同学的信息

MariaDB [hellodb]> SELECT * FROM students WHERE Name LIKE 'L%';
+-------+-------------+-----+--------+---------+-----------+
| StuID | Name        | Age | Gender | ClassID | TeacherID |
+-------+-------------+-----+--------+---------+-----------+
|     8 | Lin Daiyu   |  17 | F      |       7 |      NULL |
|    14 | Lu Wushuang |  17 | F      |       3 |      NULL |
|    17 | Lin Chong   |  25 | M      |       4 |      NULL |
+-------+-------------+-----+--------+---------+-----------+
3 rows in set (0.00 sec)

DQL多表查询与视图

两张表的纵向合并: UNION

最好是拥有相同的列的字段

MariaDB [hellodb]> SELECT StuID,Name,Age,Gender FROM students 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      |
|     5 | Yu Yutong     |  26 | M      |
|     6 | Shi Qing      |  46 | M      |
|     7 | Xi Ren        |  19 | F      |
|     8 | Lin Daiyu     |  17 | F      |
|     9 | Ren Yingying  |  20 | F      |
|    10 | Yue Lingshan  |  19 | F      |
|    11 | Yuan Chengzhi |  23 | M      |
|    12 | Wen Qingqing  |  19 | F      |
|    13 | Tian Boguang  |  33 | M      |
|    14 | Lu Wushuang   |  17 | F      |
|    15 | Duan Yu       |  19 | M      |
|    16 | Xu Zhu        |  21 | M      |
|    17 | Lin Chong     |  25 | M      |
|    18 | Hua Rong      |  23 | M      |
|    19 | Xue Baochai   |  18 | F      |
|    20 | Diao Chan     |  19 | F      |
|    21 | Huang Yueying |  22 | F      |
|    22 | Xiao Qiao     |  20 | F      |
|    23 | Ma Chao       |  23 | M      |
|    24 | Xu Xian       |  27 | M      |
|    25 | Sun Dasheng   | 100 | M      |
|     1 | Song Jiang    |  45 | M      |
|     2 | Zhang Sanfeng |  94 | M      |
|     3 | Miejue Shitai |  77 | F      |
|     4 | Lin Chaoying  |  93 | F      |
+-------+---------------+-----+--------+
29 rows in set (0.00 sec)

UNION去重(默认)

 SELECT * FROM students UNION SELECT * FROM students;

UNION ALL 不去重

DISTINCT去重

SELECT DISTINCT * FROM students;

横向合并

bash中的横向合并paste A B

[root@localhost ~]# seq 10 > f1
[root@localhost ~]# seq 10 20 > f2
[root@localhost ~]# paste f1 f2
1	10
2	11
3	12
4	13
5	14
6	15
7	16
8	17
9	18
10	19
	20
# 在paste合并中,是f1文件的第1..n行与f2文件的1..n行合并

交叉连接

第一张表的每一行都与第二章表的全部行合并组合一次

这种合并叫做交叉连接,又称为笛卡尔合并,在数据库中叫CROSS JOIN

SELECT * FROM students CROSS JOIN SELECT * FROM teachers;

多表的内连接INNER JOIN(交集)

MariaDB [hellodb]> SELECT * FROM students INNER JOIN teachers ON students.teacherid=teachers.tid;
+-------+-------------+-----+--------+---------+-----------+-----+---------------+-----+--------+
| StuID | Name        | Age | Gender | ClassID | TeacherID | TID | Name          | Age | Gender |
+-------+-------------+-----+--------+---------+-----------+-----+---------------+-----+--------+
|     5 | Yu Yutong   |  26 | M      |       3 |         1 |   1 | Song Jiang    |  45 | M      |
|     1 | Shi Zhongyu |  22 | M      |       2 |         3 |   3 | Miejue Shitai |  77 | F      |
|     4 | Ding Dian   |  32 | M      |       4 |         4 |   4 | Lin Chaoying  |  93 | F      |
+-------+-------------+-----+--------+---------+-----------+-----+---------------+-----+--------+

注意:如果定了别名,就一点得使用别名

# 老式写法
MariaDB [hellodb]> SELECT s.stuid, s.name , s.age,t.tid,t.name,t.age FROM students s ,teachers t where s.teacherid = t.tid;
+-------+-------------+-----+-----+---------------+-----+
| stuid | name        | age | tid | name          | age |
+-------+-------------+-----+-----+---------------+-----+
|     5 | Yu Yutong   |  26 |   1 | Song Jiang    |  45 |
|     1 | Shi Zhongyu |  22 |   3 | Miejue Shitai |  77 |
|     4 | Ding Dian   |  32 |   4 | Lin Chaoying  |  93 |
+-------+-------------+-----+-----+---------------+-----+
3 rows in set (0.00 sec)

ORM生成SQL语句

外连接

左外连接 LEFT OUTER JOIN

左边表的内容全要,而右边表只要交集

SELECT * FROM students LEFT OUTER JOIN teachers ON students.teacherid=teachers.tid;

没有对应关系的则显示NULL

右外连接 RIGHT OUTER JOIN

右边表内容全要,而左边的只要交集

SELECT * FROM students RIGHT OUTER JOIN teachers ON students.teacherid=teachers.tid;

在连表之后继续筛选 AND

SELECT * FROM students INNER JOIN teachers ON students.teacherid=teachers.tid AND students.age > 30;

完全外连接(并集)

默认mysql不支持全外连接,但是可以通过UNION将左外连接与右外连接合并

SELECT * FROM students LEFT OUTER JOIN teachers ON students.teacherid=teachers.tid

UNION

SELECT * FROM students RIGHT OUTER JOIN teachers ON students.teacherid=teachers.tid;

完全外连接后排除交集的部分

SELECT * FROM students LEFT OUTER JOIN teachers ON students.teacherid=teachers.tid

UNION

SELECT * FROM students RIGHT OUTER JOIN teachers ON students.teacherid=teachers.tid

WHERE students.teacherid=teachers.tid IS NULL

OR students.teacherid=teachers.tid IS NULL;

子查询

SELECT 嵌入于另一个SELECT语句中

查询年龄大于班级平均年龄的名单

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 |
|     4 | Ding Dian    |  32 | M      |       4 |         4 |
|     6 | Shi Qing     |  46 | M      |       5 |      NULL |
|    13 | Tian Boguang |  33 | M      |       2 |      NULL |
|    25 | Sun Dasheng  | 100 | M      |    NULL |      NULL |
+-------+--------------+-----+--------+---------+-----------+
5 rows in set (0.00 sec)

UPDATE students SET age=(SELECT AVG(age) FROM teachers) WHERE stuid=25;

自连接

将一张表想象成两张表来自己连接自己(以取不同别名的形式)

SELECT e.name ,l.name FROM emp AS e INNER JOIN emp AS l ON e.leaderid=l.id

多表查询

先关联起两张表,再关联第三张表

MariaDB [hellodb]> SELECT * FROM scores;
+----+-------+----------+-------+
| ID | StuID | CourseID | Score |
+----+-------+----------+-------+
|  1 |     1 |        2 |    77 |
|  2 |     1 |        6 |    93 |
|  3 |     2 |        2 |    47 |
|  4 |     2 |        5 |    97 |
|  5 |     3 |        2 |    88 |
|  6 |     3 |        6 |    75 |
|  7 |     4 |        5 |    71 |
|  8 |     4 |        2 |    89 |
|  9 |     5 |        1 |    39 |
| 10 |     5 |        7 |    63 |
| 11 |     6 |        1 |    96 |
| 12 |     7 |        1 |    86 |
| 13 |     7 |        7 |    83 |
| 14 |     8 |        4 |    57 |
| 15 |     8 |        3 |    93 |
+----+-------+----------+-------+
15 rows in set (0.00 sec)

将students 表与scores表连接

MariaDB [hellodb]> SELECT st.name,sc.courseid,sc.score FROM students AS st INNER JOIN scores AS sc ON st.stuid=sc.stuid;
+-------------+----------+-------+
| name        | courseid | score |
+-------------+----------+-------+
| Shi Zhongyu |        2 |    77 |
| Shi Zhongyu |        6 |    93 |
| Shi Potian  |        2 |    47 |
| Shi Potian  |        5 |    97 |
| Xie Yanke   |        2 |    88 |
| Xie Yanke   |        6 |    75 |
| Ding Dian   |        5 |    71 |
| Ding Dian   |        2 |    89 |
| Yu Yutong   |        1 |    39 |
| Yu Yutong   |        7 |    63 |
| Shi Qing    |        1 |    96 |
| Xi Ren      |        1 |    86 |
| Xi Ren      |        7 |    83 |
| Lin Daiyu   |        4 |    57 |
| Lin Daiyu   |        3 |    93 |
+-------------+----------+-------+
15 rows in set (0.00 sec)

在将此表格与course表连接

MariaDB [hellodb]> SELECT st.name,co.Course,sc.score FROM students AS st INNER JOIN scores AS sc ON st.stuid=sc.stuid INNER JOIN courses AS co ON sc.courseid=co.CourseID;
+-------------+----------------+-------+
| name        | Course         | score |
+-------------+----------------+-------+
| Shi Zhongyu | Kuihua Baodian |    77 |
| Shi Zhongyu | Weituo Zhang   |    93 |
| Shi Potian  | Kuihua Baodian |    47 |
| Shi Potian  | Daiyu Zanghua  |    97 |
| Xie Yanke   | Kuihua Baodian |    88 |
| Xie Yanke   | Weituo Zhang   |    75 |
| Ding Dian   | Daiyu Zanghua  |    71 |
| Ding Dian   | Kuihua Baodian |    89 |
| Yu Yutong   | Hamo Gong      |    39 |
| Yu Yutong   | Dagou Bangfa   |    63 |
| Shi Qing    | Hamo Gong      |    96 |
| Xi Ren      | Hamo Gong      |    86 |
| Xi Ren      | Dagou Bangfa   |    83 |
| Lin Daiyu   | Taiji Quan     |    57 |
| Lin Daiyu   | Jinshe Jianfa  |    93 |
+-------------+----------------+-------+
15 rows in set (0.00 sec)

视图:虚拟表

将一个复杂的语句,转变为一个视图,影藏了数据库的复杂性,类似于一张虚拟表

创建VIEW

CREAT VIEW VIEW_NAME

将上文中查询的表格定义成一个VIEW

MariaDB [hellodb]> CREATE VIEW view_test AS SELECT st.name,co.Course,sc.score FROM students AS st INNER JOIN scores AS sc ON st.stuid=sc.stuid INNER JOIN courses AS co ON sc.courseid=co.CourseID;
Query OK, 0 rows affected (0.00 sec)

MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
| view_test         |
+-------------------+
8 rows in set (0.00 sec)

检查一张表是否为视图

MariaDB [hellodb]> show table status like 'view_test'\G
*************************** 1. row ***************************
           Name: view_test
         Engine: NULL
        Version: NULL
     Row_format: NULL
           Rows: NULL
 Avg_row_length: NULL
    Data_length: NULL
Max_data_length: NULL
   Index_length: NULL
      Data_free: NULL
 Auto_increment: NULL
    Create_time: NULL
    Update_time: NULL
     Check_time: NULL
      Collation: NULL
       Checksum: NULL
 Create_options: NULL
        Comment: VIEW # 显示为一个视图
1 row in set (0.01 sec)

视图现在已经不建议使用

删除视图

MariaDB [hellodb]> DROP VIEW view_test;
Query OK, 0 rows affected (0.00 sec)

MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
7 rows in set (0.00 sec)

函数存储过程、触发器及用户管理

函数

Function and Operator Reference

系统自带函数

自定义函数

  • 保存在mysql.proc表中
  • 创建UDF
CREATE [AGGREGATE] FUNCTION function_name(parameter_name type,[parameter_name type,...])
RETURNS {STRING|INTEGER|REAL}
runtime_body

说明:

参数可以有多个,也可以没有参数
必须有且只有一个返回值,不能返回多个值

创建函数

创建一个简单的无参数函数

CREATE FUNCTION simpleFun() RETURNS VARCHAR(20) RETURN "Hello World!";

使用函数是必须嵌入在SELECT语句中

SELECT simpleFun();

MariaDB [hellodb]> SELECT simpleFun();
+--------------+
| simpleFun()  |
+--------------+
| Hello World! |
+--------------+
1 row in set (0.00 sec)

查看函数列表

SHOW FUNCTION STATUS
# 竖着显示
MariaDB [hellodb]> SHOW FUNCTION STATUS \G
*************************** 1. row ***************************
                  Db: hellodb
                Name: simpleFun
                Type: FUNCTION
             Definer: root@localhost
            Modified: 2020-06-29 14:15:16
             Created: 2020-06-29 14:15:16
       Security_type: DEFINER
             Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

查看函数定义

SHOW CREATE FUNCTION function_name

MariaDB [hellodb]> SHOW CREATE FUNCTION simpleFun \G
*************************** 1. row ***************************
            Function: simpleFun
            sql_mode: STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
     Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION `simpleFun`() RETURNS varchar(20) CHARSET utf8
RETURN "Hello World!"
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

或者直接查看mysql.proc

MariaDB [hellodb]> SELECT * FROM mysql.proc \G
*************************** 1. row ***************************
                  db: mysql
                name: AddGeometryColumn
                type: PROCEDURE
       specific_name: AddGeometryColumn
            language: SQL
     sql_data_access: CONTAINS_SQL
    is_deterministic: NO
       security_type: INVOKER
          param_list: catalog varchar(64), t_schema varchar(64),
   t_name varchar(64), geometry_column varchar(64), t_srid int
             returns: 
                body: begin
  set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' ADD ', geometry_column,' GEOMETRY REF_SYSTEM_ID=', t_srid); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end
             definer: root@localhost
             created: 2020-06-26 21:10:47
            modified: 2020-06-26 21:10:47
            sql_mode: 
             comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
        db_collation: latin1_swedish_ci
           body_utf8: begin
  set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' ADD ', geometry_column,' GEOMETRY REF_SYSTEM_ID=', t_srid); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end
*************************** 2. row ***************************
                  db: mysql
                name: DropGeometryColumn
                type: PROCEDURE
       specific_name: DropGeometryColumn
            language: SQL
     sql_data_access: CONTAINS_SQL
    is_deterministic: NO
       security_type: INVOKER
          param_list: catalog varchar(64), t_schema varchar(64),
   t_name varchar(64), geometry_column varchar(64)
             returns: 
                body: begin
  set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' DROP ', geometry_column); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end
             definer: root@localhost
             created: 2020-06-26 21:10:47
            modified: 2020-06-26 21:10:47
            sql_mode: 
             comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
        db_collation: latin1_swedish_ci
           body_utf8: begin
  set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' DROP ', geometry_column); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end
*************************** 3. row ***************************
                  db: hellodb
                name: simpleFun
                type: FUNCTION
       specific_name: simpleFun
            language: SQL
     sql_data_access: CONTAINS_SQL
    is_deterministic: NO
       security_type: DEFINER
          param_list: 
             returns: varchar(20) CHARSET utf8
                body: RETURN "Hello World!"
             definer: root@localhost
             created: 2020-06-29 14:15:16
            modified: 2020-06-29 14:15:16
            sql_mode: STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
             comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
        db_collation: utf8_general_ci
           body_utf8: RETURN "Hello World!"
3 rows in set (0.00 sec)

删除UDF

DROP FUNCTION function_name

自定义函数

DELIMITER //
CREATE FUNCTION deleteById(uid SMALLINT UNSIGNED) RETURNS VARCHAR(20)
BEGIN
DELETE FROM students WHERE stuid = uid;
RETURN (SELECT COUNT(stuid) FROM students);
END//
DELIMITER ;
MariaDB [hellodb]> DELIMITER //
MariaDB [hellodb]> CREATE FUNCTION deleteById(uid SMALLINT UNSIGNED) RETURNS VARCHAR(20)
    -> BEGIN
    -> DELETE FROM students WHERE stuid = uid;
    -> RETURN (SELECT COUNT(stuid) FROM students);
    -> END//
Query OK, 0 rows affected (0.00 sec)

MariaDB [hellodb]> DELIMITER ;

定义函数内部变量DECLARE 变量1[,变量2,... ]变量类型 [DEFAULT 默认值]

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(id) FROM tdb_name INTO x;
RETURN x;
END//

调用自定义函数语法

SELECT function_name(parameter_value,...)
MariaDB [hellodb]> SELECT deleteById(10);
+----------------+
| deleteById(10) |
+----------------+
| 24             |
+----------------+
1 row in set (0.01 sec)

存储过程

存储过程优势

  • 存储过程把经常使用的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表示参数的类型

创建无参存储过程

delimiter //
CREATE PROCEDURE showTime()
BEGIN
SELECT now();
END//
delimiter ;
CALL showTime;

调用

MariaDB [hellodb]> delimiter //
MariaDB [hellodb]> CREATE PROCEDURE showTime()
    -> BEGIN
    -> SELECT now();
    -> END//
Query OK, 0 rows affected (0.00 sec)

MariaDB [hellodb]> delimiter ;

##############################################################
MariaDB [hellodb]> CALL showTime;
+---------------------+
| now()               |
+---------------------+
| 2020-06-29 14:40:46 |
+---------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

创建含参存储过程:只有一个IN参数

delimiter //
CREATE PROCEDURE selectById(IN uid SMALLINT UNSIGNED)
BEGIN
SELECT * FROM students WHERE stuid = uid;
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;

# @sum = 5050
# @i = 101

创建含参存储过程:包含IN参数和OUT参数

delimiter //
CREATE PROCEDURE deleteById(IN uid SMALLINT UNSIGNED, OUT num SMALLINT UNSIGNED)
BEGIN
DELETE FROM students WHERE stuid >= uid;
SELECT row_count() into num;
END//
delimiter ;
call deleteById(2,@Line);
SELECT @Line;

说明:创建存储过程deleteById,包含一个IN参数和一个OUT参数.调用时,传入删除的ID和保存被修改的行数值的用户变量@Line,select @Line;输出被影响行数

查看存储过程列表

SHOW PROCEDURE STATUS;

查看存储过程定义

SHOW CREATE PROCEDURE sp_name

调用存储过程CALL

CALL sp_name ([ proc_parameter [,proc_parameter ...]])
CALL sp_name
#说明:当无参时,可以省略"()",当有参数时,不可省略"()”

存储过程修改

ALTER语句修改存储过程只能修改存储过程的注释等无关紧要的东西,不能修改存储过程体,所以要修改存储过程,方法就是删除重建

删除存储过程

DROP PROCEDURE [IF EXISTS] sp_name

流程控制

存储过程和函数中可以使用流程控制来控制语句的执行
流程控制:

  • IF:用来进行条件判断。根据是否满足条件,执行不同语句
  • CASE:用来进行条件判断,可实现比IF语句更复杂的条件判断
  • LOOP:重复执行特定的语句,实现一个简单的循环
  • LEAVE:用于跳出循环控制
  • ITERATE:跳出本次循环,然后直接进入下一次循环
  • REPEAT:有条件控制的循环语句。当满足特定条件时,就会跳出循环语句
  • WHILE:有条件控制的循环语句

触发器

触发器的执行不是由程序调用,也不是由手工启动,而是由事件来触发、激活从而实现执行

创建触发器

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:该触发器作用在表名

触发器示例

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);

示例:创建触发器,在向学生表INSERT数据时,学生数增加,DELETE学生时,学生数减少

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;
Database changed

SELECT * FROM triggers WHERE trigger_name='trigger_student_count_insert';

删除触发器

DROP TRIGGER trigger_name;

MYSQL用户和权限管理

元数据数据库:mysql
系统授权表:

  • db, host, user
  • columns_priv, tables_priv, procs_priv, proxies_priv

用户账号:

  • ‘USERNAME’@‘HOST’
    • @‘HOST’:
      主机名
      IP地址或Network
      通配符: % _
      示例:172.16.%.%

用户账户位置

MariaDB [mysql]> SELECT user,host,password from user;
+------+-----------------------+----------+
| user | host                  | password |
+------+-----------------------+----------+
| root | localhost             |          |
| root | localhost.localdomain |          |
| root | 127.0.0.1             |          |
| root | ::1                   |          |
|      | localhost             |          |
|      | localhost.localdomain |          |
+------+-----------------------+----------+
6 rows in set (0.00 sec)

注意其他版本账户管理信息可能会放在authentication_string列中

MariaDB [mysql]> SELECT user,host,password,authentication_string from user;
+------+-----------------------+----------+-----------------------+
| user | host                  | password | authentication_string |
+------+-----------------------+----------+-----------------------+
| root | localhost             |          |                       |
| root | localhost.localdomain |          |                       |
| root | 127.0.0.1             |          |                       |
| root | ::1                   |          |                       |
|      | localhost             |          |                       |
|      | localhost.localdomain |          |                       |
+------+-----------------------+----------+-----------------------+
6 rows in set (0.00 sec)

创建用户

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';

修改密码

SET PASSWORD FOR 'user'@'host' = PASSWORD(‘password');

有时候mysql会自动将127.0.0.1反向解析成localhost

因此我们关闭反向解析的操作的变量为skip_name_resolve

[root@localhost ~]# vim /etc/my.cnf

[musqld]
skip_name_resolve

####重启服务#####
systemctl restart mariadb

用UPDATE命令直接更改数据库表

UPDATE mysql.user SET password=PASSWORD('password') WHERE clause;
# 此方法需要执行下面指令才能生效:
FLUSH PRIVILEGES;

破解口令方法

在配置文件中加入skip_grant_tables与skip_networking,再重新启动

为了数据库的安全,必须加入跳过远程登录选项!

MYSQL架构和存储引擎详解

MYSQL权限类别

管理类

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 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
# 示例:GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO 'someuser'@'somehost‘;

GRANT Statement

示例

GRANT ALL ON hellodb.* TO test@'192.168.37.%' IDENTIFIED BY 'centos';

MariaDB [hellodb]> SELECT user,host,password FROM mysql.user;
+--------+-----------------------+-------------------------------------------+
| user   | host                  | password                                  |
+--------+-----------------------+-------------------------------------------+
| root   | localhost             |                                           |
| root   | localhost.localdomain |                                           |
| root   | 127.0.0.1             |                                           |
| root   | ::1                   |                                           |
|        | localhost             |                                           |
|        | localhost.localdomain |                                           |
| magedu | 192.168.1.%           | *128977E278358FF80A246B5046F51043A2B1FCED |
| test   | 192.168.37.%          | *128977E278358FF80A246B5046F51043A2B1FCED |
+--------+-----------------------+-------------------------------------------+
8 rows in set (0.00 sec)


查看授权用户信息

MariaDB [hellodb]> SHOW GRANTS FOR test@'192.168.37.%'\G;
*************************** 1. row ***************************
Grants for [email protected].%: GRANT USAGE ON *.* TO 'test'@'192.168.37.%' IDENTIFIED BY PASSWORD '*128977E278358FF80A246B5046F51043A2B1FCED'
*************************** 2. row ***************************
Grants for [email protected].%: GRANT ALL PRIVILEGES ON `hellodb`.* TO 'test'@'192.168.37.%'
2 rows in set (0.00 sec)

回收授权REVOKE

取消删除表格权利

REVOKE DELETE ON hellodb.* FROM test@'192.168.37.%';

MariaDB [hellodb]> SHOW GRANTS FOR test@'192.168.37.%' \G;
*************************** 1. row ***************************
Grants for [email protected].%: GRANT USAGE ON *.* TO 'test'@'192.168.37.%' IDENTIFIED BY PASSWORD '*128977E278358FF80A246B5046F51043A2B1FCED'
*************************** 2. row ***************************
Grants for [email protected].%: GRANT SELECT, INSERT, UPDATE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `hellodb`.* TO 'test'@'192.168.37.%'

# 取消DROP同理

查看当前用户权限

MariaDB [hellodb]> SHOW GRANTS FOR CURRENT_USER();
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION       |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)

注意:MariaDB服务进程启动时会读取mysql库中所有授权表至内存
(1) GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效
(2) 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:mysql> FLUSH PRIVILEGES;

练习

数据库授权magedu用户,允许192.168.1.0/24网段可以连接mysql

MariaDB [mysql]> CREATE USER magedu@'192.168.1.%' IDENTIFIED BY 'centos';
Query OK, 0 rows affected (0.00 sec)

检查用户表

MariaDB [mysql]> SELECT user,host,password from user;
+--------+-----------------------+-------------------------------------------+
| user   | host                  | password                                  |
+--------+-----------------------+-------------------------------------------+
| root   | localhost             |                                           |
| root   | localhost.localdomain |                                           |
| root   | 127.0.0.1             |                                           |
| root   | ::1                   |                                           |
|        | localhost             |                                           |
|        | localhost.localdomain |                                           |
| magedu | 192.168.1.%           | *128977E278358FF80A246B5046F51043A2B1FCED |
+--------+-----------------------+-------------------------------------------+
7 rows in set (0.00 sec)


MariaDB [mysql]> SELECT * FROM user WHERE user='magedu' \G;
*************************** 1. row ***************************
                  Host: 192.168.1.%
                  User: magedu
              Password: *128977E278358FF80A246B5046F51043A2B1FCED
           Select_priv: N
           Insert_priv: N
           Update_priv: N
           Delete_priv: N
           Create_priv: N
             Drop_priv: N
           Reload_priv: N
         Shutdown_priv: N
          Process_priv: N
             File_priv: N
            Grant_priv: N
       References_priv: N
            Index_priv: N
            Alter_priv: N
          Show_db_priv: N
            Super_priv: N
 Create_tmp_table_priv: N
      Lock_tables_priv: N
          Execute_priv: N
       Repl_slave_priv: N
      Repl_client_priv: N
      Create_view_priv: N
        Show_view_priv: N
   Create_routine_priv: N
    Alter_routine_priv: N
      Create_user_priv: N
            Event_priv: N
          Trigger_priv: N
Create_tablespace_priv: N
              ssl_type: 
            ssl_cipher: 
           x509_issuer: 
          x509_subject: 
         max_questions: 0
           max_updates: 0
       max_connections: 0
  max_user_connections: 0
                plugin: 
 authentication_string: 
      password_expired: N
               is_role: N
          default_role: 
    max_statement_time: 0.000000
1 row in set (0.00 sec)

ERROR: No query specified

MYSQL架构

从入门到删库跑路的过程_第3张图片

存储引擎

Feature MyISAM Memory InnoDB Archive NDB
B-tree indexes Yes Yes Yes No No
Backup/point-in-time recovery Yes Yes Yes Yes Yes
Cluster database support No No No No Yes
Clustered indexes No No Yes No No
Compressed data Yes No Yes Yes No
Data caches No N/A Yes No Yes
Encrypted data Yes Yes Yes Yes Yes
Foreign key support No No Yes No Yes
Full-text search indexes Yes No Yes No No
Geospatial data type support Yes No Yes Yes Yes
Geospatial indexing support Yes No Yes No No
Hash indexes No Yes No No Yes
Index caches Yes N/A Yes No Yes
Locking granularity Table Table Row Row Row
MVCC No No Yes No No
Replication support Yes Limited Yes Yes Yes
Storage limits 256TB RAM 64TB None 384EB
T-tree indexes No No No No Yes
Transactions No No Yes No Yes
Update statistics for data dictionary Yes Yes Yes Yes Yes

Transactions 事务

特性:

  • 原子性
    • 一个事务是由多个小的步骤组成,要么所有步骤都完成,要么什么也不做

MyISAM引擎特点

  • 不支持事务
  • 表级锁定
  • 读写相互阻塞,写入不能读,读时不能写
  • 只缓存索引
  • 不支持外键约束
  • 不支持聚簇索引
  • 读取数据较快,占用资源较少
  • 不支持MVCC(多版本并发控制机制)高并发
  • 崩溃恢复性较差
  • MySQL5.5.5前默认的数据库引擎

MyISAM存储引擎适用场景
只读(或者写较少)、表较小(可以接受长时间进行修复操作)

MyISAM引擎文件

  • tbl_name.frm 表格式定义
  • tbl_name.MYD 数据文件
  • tbl_name.MYI 索引文件

InnoDB引擎特点

  • 行级锁
  • 支持事务,适合处理大量短期事务
  • 读写阻塞与事务隔离级别相关
  • 可缓存数据和索引
  • 支持聚簇索引
  • 崩溃恢复性更好
  • 支持MVCC高并发
  • 从MySQL5.5后支持全文索引
  • 从MySQL5.5.5开始为默认的数据库引擎

InnoDB数据库文件

  • 所有InnoDB表的数据和索引放置于同一个表空间中
    表空间文件:datadir定义的目录下
    数据文件:ibddata1, ibddata2, …
  • 每个表单独使用一个表空间存储表的数据和索引
    启用:innodb_file_per_table=ON
    参看:https://mariadb.com/kb/en/library/xtradbinnodb-server-system-variables/#innodb_file_per_table
    ON (>= MariaDB 5.5)
  • 两类文件放在数据库独立目录中
    数据文件(存储数据和索引):tb_name.ibd
    表格式定义:tb_name.frm

其他存储引擎

  • Performance_Schema:Performance_Schema数据库使用

  • Memory :将所有数据存储在RAM中,以便在需要快速查找参考和其他类似数据的环境中进行快速访问。适用存放临时数据。引擎以前被称为HEAP引擎

  • MRG_MyISAM:使MySQL DBA或开发人员能够对一系列相同的MyISAM表进行逻辑分组,并将它们作为一个对象引用。适用于VLDB(Very Large Data Base)环境,如数据仓库

  • Archive :为存储和检索大量很少参考的存档或安全审核信息,只支持SELECT和INSERT操作;支持行级锁和专用缓存区

  • Federated联合:用于访问其它远程MySQL服务器一个代理,它通过创建一个到远程MySQL服务器的客户端连接,并将查询传输到远程服务器执行,而后完成数据存取,提供链接单独MySQL服务器的能力,以便从多个物理服务器创建一个逻辑数据库。非常适合分布式或数据集市环境

  • BDB:可替代InnoDB的事务引擎,支持COMMIT、ROLLBACK和其他事务特性

  • Cluster/NDB:MySQL的簇式数据库引擎,尤其适合于具有高性能查找要求的应用程序,这类查找需求还要求具有最高的正常工作时间和可用性

  • CSV:CSV存储引擎使用逗号分隔值格式将数据存储在文本文件中。可以使用CSV引擎以CSV格式导入和导出其他软件和应用程序之间的数据交换

  • BLACKHOLE :黑洞存储引擎接受但不存储数据,检索总是返回一个空集。该功能可用于分布式数据库设计,数据自动复制,但不是本地存储

  • example:“stub”引擎,它什么都不做。可以使用此引擎创建表,但不能将数据存储在其中或从中检索。目的是作为例子来说明如何开始编写新的存储引擎

管理存储引擎

查看mysql支持的存储引擎

SHOW ENGINES \G;

查看当前默认的存储引擎

SHOW VARIABLES LIKE '%storage_engine%';

设置默认的存储引擎

vim /etc/my.conf
[mysqld]
default_storage_engine= InnoDB

查看库中所有表使用的存储引擎

SHOW TABLE STATUS FROM db_name;

查看库中指定表的存储引擎

SHOW TABLE STATUS LIKE 'tb_name';
SHOW CREATE TABLE tb_name;

设置表的存储引擎

CREATE TABLE tb_name(... ) ENGINE=InnoDB;
ALTER TABLE tb_name ENGINE=InnoDB;

你可能感兴趣的:(基础作业,数据库,mysql,mariadb)