MySQL是一个关系型数据库管理系统
一、数据库管理系统
数据库管理系统(Database Management System)是一种操纵和管理数据库的大型软件,用于建立、使用和维护数据库,简称DBMS。
数据库管理系统就是实现把用户意义下抽象的逻辑数据处理,转换成为计算机中具体的物理数据处理的软件。有了数据库管理系统,用户就可以在抽象意义下处理数据,而不必顾及这些数据在计算机中的布局和物理位置。
1、DBMS的基本结构:
分析器先分析SQL语句,然后交给操作求解器生成执行路径,再由计划执行器生成执行计划,并由优化器进行优化
2、DBMS的优点:
数据独立性
高效数据存取
数据完整性(事务)和安全性
数据管理
并发控制(琐机制)和故障恢复
开发周期缩短
二、关系型数据库基础理论
1、关系数据库的组件:
库:表的集合,每个表都有一个惟一的名字
表(关系):由行(row, record, tuple)和列(field, column, attribute)组成
行:代表一组数据之间的联系;
列:有其允许取值的集合,称之为该属性域;
2、约束:
主键(primary key):属于惟一键,但其值不能为空
惟一键(unique key)
外键(foreign key):引用性约束
检查性约束
3、事务
事务(Transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元(unit)
事务是恢复和并发控制的基本单位,其有4个属性(通常称为ACID属性):
原子性(atomicity):一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
一致性(consistency):事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
隔离性(isolation):一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
持久性(durability):持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的
4、SQL
SQL(Structured Query Language,结构化查询语言)是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统
⑴SQL语言有如下几个部分组成:
①数据定义语言:DDL;定义关系,修改关系,删除关系
完整性(intigrity):定义完整性约束的命令,隶属于DDL
视图定义:管理视图view(虚表);
授权:定义对表或视图的访问权限;
DDL: CREATE, DROP, ALTER, GRANT, REVOKE
②数据操纵语言:DML;插入行、修改行、删除行
DML: INSERT, DELETE, UPDATE, SELECT
③事务控制:创建事务和结束事务
⑵SQL的数据定义:
创建关系,即创建表:
每个关系模式;
每个属性的取值类型;
完整性约束;
索引的集合;
表的安全性和权限信息;
表的物理存储结构:因存储引擎不同而不同
MyISAM:.frm, .MYD(数据), .MYI(索引)
InnoDB:.frm, .ibd(数据+索引)
⑶SQL数据的类型:(以mysql为例)
字符型:
固定长度:CHAR
可变长度:VARCHAR
mysql:BINARY, VARBINARY
数值型:
精确数值型:
int:tinyint, smallint, mediumint, int, bigint
近似数值型:
float、double
日期时间型:
date、time、datetime、year(4)、year(2)
内置类型:
ENUM、SET
类型修饰:
NULL、NOT NULL、DEFAULT
数值型:
UNSIGNED: 无符号
整数:AUTO_INCREMENT(前提:字段必须为主键或惟一键)
键:
PRIMARY KEY
UNIQUE KEY
5、常见的关系型数据库
Oracle、Sybase、Infomix、DB2、SQL Server、MySQL --> MariaDB(MariaDB是MySQL的衍生版)
三、mysql的安装及使用
1、MySQL安装方式:
①rpm包安装
OS vendor、项目方提供
②通用二进制格式
展开、配置后即可使用
③源码编译安装
要用cmake编译
2、MySQL(MariaDB)服务端:监听于3306/tcp
①CentOS 6.5:mysql-server(rpm包名),mysqld(服务进程)
服务脚本:/etc/rc.d/init.d/mysqld
主服务程序:/usr/bin/mysqld_safe
数据目录:/var/lib/mysql
配置文件:/etc/my.cnf(服务端和客户端共用)
客户端程序:/usr/bin/mysql
unix sock: /var/lib/mysql/mysql.sock
mysqld第一次启动之前需要先初始化:创建mysqld服务自身运行所依赖的元数据库mysql
②CentOS 7:mariadb-server,mysqld
# systemctl start mariadb.service
[root@node2 ~]# yum -y install mysql-server ... Installed: mysql-server.x86_64 0:5.1.73-5.el6_6 Dependency Installed: #安装服务端程序会一并安装mysql客户端程序和mysql-libs mysql.x86_64 0:5.1.73-5.el6_6 mysql-libs.x86_64 0:5.1.73-5.el6_6 perl-DBD-MySQL.x86_64 0:4.013-3.el6 perl-DBI.x86_64 0:1.609-4.el6 Complete! [root@node2 ~]# rpm -ql mysql-server /etc/logrotate.d/mysqld /etc/rc.d/init.d/mysqld #服务脚本 /usr/bin/innochecksum /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_fix_privilege_tables /usr/bin/mysql_install_db /usr/bin/mysql_secure_installation ... /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_fix_privilege_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 /var/lib/mysql #默认的数据目录 /var/log/mysqld.log /var/run/mysqld [root@node2 ~]# rpm -ql mysql-libs /etc/ld.so.conf.d/mysql-x86_64.conf /etc/my.cnf #配置文件 /usr/lib64/mysql /usr/lib64/mysql/libmysqlclient.so.16 /usr/lib64/mysql/libmysqlclient.so.16.0.0 /usr/lib64/mysql/libmysqlclient_r.so.16 /usr/lib64/mysql/libmysqlclient_r.so.16.0.0 ... [root@node2 ~]# service mysqld start Initializing MySQL database: WARNING: The host 'node2' could not be looked up with resolveip. This probably means that your libc libraries are not 100 % compatible with this binary MySQL version. The MySQL daemon, mysqld, should work normally with the exception that host name resolving will not work. This means that you should use IP addresses instead of hostnames when specifying MySQL privileges ! Installing MySQL system tables... OK Filling help tables... OK To start mysqld at boot time you have to copy support-files/mysql.server to the right place for your system PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER ! To do so, start the server, then issue the following commands: /usr/bin/mysqladmin -u root password 'new-password' /usr/bin/mysqladmin -u root -h node2 password 'new-password' Alternatively you can run: /usr/bin/mysql_secure_installation which will also give you the option of removing the test databases and anonymous user created by default. This is strongly recommended for production servers. See the manual for more instructions. You can start the MySQL daemon with: cd /usr ; /usr/bin/mysqld_safe & You can test the MySQL daemon with mysql-test-run.pl cd /usr/mysql-test ; perl mysql-test-run.pl Please report any problems with the /usr/bin/mysqlbug script! [ OK ] Starting mysqld: [ OK ] [root@node2 ~]# netstat -tlnp #3306端口已监听 ... tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 4549/mysqld ...
3、mysql客户端的基本使用
⑴连接数据库
mysql
-u USERNAME: 默认为root
-h SERVER: 默认为localhost
-p [PASSWORD]: 输入密码
例如 mysql -h 192.168.30.20 -u root -p abc123
mysql的用户账号:USERNAME@HOST
USERNAME: 用户名
HOST: 仅允许此用户通过此处指定的主机登录mysqld服务;
例如root@localhost, root@'127.0.0.1', root@'HOSTNAME'
mysql服务端在初始化时会创建一个root@localhost的账号,但没有密码,需手动创建。此root用户跟linux系统的root用户无关
⑵交互式命令:
客户端命令:无需分号结尾
mysql> help #查看有哪些客户端命令
服务器端命令:必需分号结尾
[root@node2 ~]# mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.1.73 Source distribution Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> help #查看可使用的客户端命令 For information about MySQL products and services, visit: http://www.mysql.com/ For developer information, including the MySQL Reference Manual, visit: http://dev.mysql.com/ To buy MySQL Enterprise support, training, or other products, visit: https://shop.mysql.com/ 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' mysql> select version(); #查看mysql服务端版本 +-----------+ | version() | +-----------+ | 5.1.73 | +-----------+ 1 row in set (0.03 sec) mysql> select user(); #查看有哪些mysql用户 +----------------+ | user() | +----------------+ | root@localhost | +----------------+ 1 row in set (0.00 sec) mysql> select current_user(); #查看当前mysql用户 +----------------+ | current_user() | +----------------+ | root@localhost | +----------------+ 1 row in set (0.00 sec)
4、设置或修改用户密码
mysqladmin -u 用户名 -p 旧密码 password 新密码
因为初始时root没有密码,所以-p旧密码一项可以省略
[root@node2 ~]# mysqladmin -u root password mysql #给root用户设置密码 [root@node2 ~]# mysql -p Enter password: ... mysql>
四、mysql的使用和维护
注意:在mysql中,命令和关键字不区分大小写,但库名、表名、字段名等区分大小写
1、DDL
①管理数据库:
CREATE DATABASE DB_NAME;
DROP DATABASE DB_NAME;
SHOW DATABASES;
USE DB_NAME;
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | test | +--------------------+ 3 rows in set (0.00 sec) mysql> use mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show tables; #查看当前数据库中有哪些表 +---------------------------+ | Tables_in_mysql | +---------------------------+ | columns_priv | | db | | event | | func | | general_log | | help_category | | help_keyword | | help_relation | | help_topic | | host | | ndb_binlog_index | | plugin | | proc | | procs_priv | | servers | | slow_log | | tables_priv | | time_zone | | time_zone_leap_second | | time_zone_name | | time_zone_transition | | time_zone_transition_type | | user | #用户账号表 +---------------------------+ 23 rows in set (0.00 sec) mysql> create database testdb; Query OK, 1 row affected (0.26 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | test | | testdb | +--------------------+ 4 rows in set (0.12 sec) mysql> drop database testdb; Query OK, 0 rows affected (0.21 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | test | +--------------------+ 3 rows in set (0.12 sec) [root@node2 ~]# cd /var/lib/mysql #创建一个数据库实际上就是在数据目录下创建一个目录,但并不建议采用这种方式 [root@node2 mysql]# mkdir testdb [root@node2 mysql]# chown -R mysql.mysql testdb mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | test | | testdb | +--------------------+ 4 rows in set (0.00 sec)
②管理表:
CREATE TABLE [DB_NAME.]TABLE_NAME (COLUMN DEFINATION);
COLUMN DEFINATION:(col1_name data_type [修饰符], col2_name data_type [修饰符])
例如 CREATE TABLE testdb.students (ID INT UNSIGNED NOT NULL UNIQUE KEY AUTO_INCREMENT, Name CHAR(10) NOT NULL, Age TINYINT, Gender ENUM('f', 'm') NOT NULL, Class VARCHAR(50));
DESC TB_NAME; #查看表定义
DROP TABLE [DB_NAME.]TABLE_NAME;
mysql> use testdb Database changed mysql> create table students (ID int unsigned not null unique key auto_increment,Name char(10) not null,Age tinyint,Gender enum('f','m') not null,Class varchar(50)); Query OK, 0 rows affected (0.10 sec) mysql> desc students; +--------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+------------------+------+-----+---------+----------------+ | ID | int(10) unsigned | NO | PRI | NULL | auto_increment | | Name | char(10) | NO | | NULL | | | Age | tinyint(4) | YES | | NULL | | | Gender | enum('f','m') | NO | | NULL | | | Class | varchar(50) | YES | | NULL | | +--------+------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)
③管理用户:
CREATE USER USERNAME@HOST [IDENTIFIED BY 'password'];
HOST表示格式:
ip、网段
MySQL的字符通配符:
%:匹配任意长度的任意字符
_:匹配任意单个字符
例如 create user tuser@'192.168.%.%' identified by 'tpass';
DROP USER USERNAME@HOST;
GRANT 权限列表 ON DB_NAME.TB_NAME TO USERNAME@HOST [IDENTIFIED BY 'new_pass'];
权限列表:
多个权限用逗号分隔
ALL PRIVILEGES,可简写为ALL
DB_NAME:
*:所有库
TB_NAME:
*: 所有表
刷新授权表,以使得权限立即生效:FLUSH PRIVILEGES;
注:若多次授权,后面的权限并不会覆盖之前的权限,而会合并
REVOKE 权限列表 ON DB_NAME.DB_TABLE FROM USERNAME@HOST;
mysql> create user tuser@'192.168.%.%' identified by 'tpass'; Query OK, 0 rows affected (0.13 sec) mysql> grant select,insert,update,delete on *.* to tuser@'192.168.%.%'; Query OK, 0 rows affected (0.07 sec) mysql> flush privileges; Query OK, 0 rows affected (0.06 sec)
2、DML:
①插入数据:
INSERT INTO tb_name [(col1, col2,...)] VALUE|VALUES (val1, val2,...)[,(val1, val2,...)];
例如mysql> INSERT INTO students (Name,Age,Gender,Class) VALUES ('jerry',43,'m','class 2'),('Ou Yangfeng',77,'m','Hamopai');
mysql> insert into students (Name,Age,Gender,Class) values ('jerry',43,'m','class 2'),('Ou Yangfeng',77,'m','Hamopai'); Query OK, 2 rows affected, 1 warning (0.09 sec) Records: 2 Duplicates: 0 Warnings: 1 #这里有警告是因为ouyangfeng已超出了字段定义的长度,mysql会自动截取。可立即使用show warings;查看警告信息
②查询数据:
SELECT 字段列表 FROM 表 WHERE 条件子句 ORDER BY 字段 [DESC];
order后面跟desc表示按倒序排序
组合条件:and、or、not
条件子句:= > < >= <= !=
BETWEEN start_value AND end_value;
LIKE: 模糊匹配
例如 Name LIKE 'j%';
RLIKE:模式匹配
例如 Name RLIKE '^j.*$'
例如 SELECT Name FROM students WHERE Age > 40;
mysql> select * from students; +----+------------+------+--------+---------+ | ID | Name | Age | Gender | Class | +----+------------+------+--------+---------+ | 1 | jerry | 43 | m | class 2 | | 2 | Ou Yangfen | 77 | m | Hamapai | +----+------------+------+--------+---------+ 2 rows in set (0.00 sec) mysql> select Name from students where Age > 50; +------------+ | Name | +------------+ | Ou Yangfen | +------------+ 1 row in set (0.07 sec) mysql> select Name from students where Age > 40 order by Age desc; +------------+ | Name | +------------+ | Ou Yangfen | | jerry | +------------+ 2 rows in set (0.01 sec) mysql> select Name from students where Name like 'j%'; +-------+ | Name | +-------+ | jerry | +-------+ 1 row in set (0.00 sec)
③删除数据:
DELETE FROM tb_name WHERE 条件子句 [LIMIT n];
④更新数据:
UPDATE tb_name SET col1=new_value1 [WHERE 条件子句];
mysql> update students set Name='ouyang ke' where Class = 'hamapai'; Query OK, 1 row affected (0.03 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from students; +----+-----------+------+--------+---------+ | ID | Name | Age | Gender | Class | +----+-----------+------+--------+---------+ | 1 | jerry | 43 | m | class 2 | | 2 | ouyang ke | 77 | m | Hamapai | +----+-----------+------+--------+---------+ 2 rows in set (0.00 sec)
3、几个常用的SHOW命令:
查看MariaDB支持哪此存储引擎:SHOW ENGINES;
查看表的属性信息:SHOW TABLE STATUS;
查看支持的字符集:SHOW CHARACTER SET;
查看排序规则:SHOW COLLATION;
查看MySQL的服务器变量或状态变量:
mysql的各种工作属性是通过其服务器变量来定义的:
SHOW {GLOBAL|SESSION} VARIALES [LIKE ''];
mysql运行时的诸多统计数据会被记录在状态变量:
SHOW {GLOBAL|SESSION} STATUS [LIKE ''];
mysql> show engines; +------------+---------+------------------------------------------------------------+--------------+------+------------+ | Engine | Support | Comment | Transactions | XA | Savepoints | +------------+---------+------------------------------------------------------------+--------------+------+------------+ | MRG_MYISAM | YES | Collection of identical MyISAM tables | NO | NO | NO | | CSV | YES | CSV storage engine | NO | NO | NO | | MyISAM | DEFAULT | Default engine as of MySQL 3.23 with great performance | NO | NO | NO | | InnoDB | YES | Supports transactions, row-level locking, and foreign keys | YES | YES | YES | | MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO | +------------+---------+------------------------------------------------------------+--------------+------+------------+ 5 rows in set (0.00 sec) mysql> show table status; +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-------------------+----------+----------------+---------+ | students | MyISAM | 10 | Dynamic | 2 | 30 | 60 | 281474976710655 | 2048 | 0 | 3 | 2015-11-20 03:51:47 | 2015-11-20 05:00:04 | NULL | latin1_swedish_ci | NULL | | | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-------------------+----------+----------------+---------+ 1 row in set (0.06 sec) mysql> show table status\G #竖排格式 *************************** 1. row *************************** Name: students Engine: MyISAM Version: 10 Row_format: Dynamic Rows: 2 Avg_row_length: 30 Data_length: 60 Max_data_length: 281474976710655 Index_length: 2048 Data_free: 0 Auto_increment: 3 Create_time: 2015-11-20 03:51:47 Update_time: 2015-11-20 05:00:04 Check_time: NULL Collation: latin1_swedish_ci #排序规则 Checksum: NULL Create_options: Comment: 1 row in set (0.01 sec) mysql> show global variables; +-----------------------------------------+-------------------------------------------------------------------------------------------+ | Variable_name | Value | +-----------------------------------------+-------------------------------------------------------------------------------------------+ | auto_increment_increment | 1 | | auto_increment_offset | 1 | | autocommit | ON | | automatic_sp_privileges | ON | | back_log | 50 | | basedir | /usr/ | | big_tables | OFF | | binlog_cache_size | 32768 | | binlog_direct_non_transactional_updates | OFF | | binlog_format | STATEMENT | | bulk_insert_buffer_size | 8388608 | | character_set_client | latin1 | | character_set_connection | latin1 | ...