关系数据库管理基础

背景知识

SQL 简介

SQL 是英文 Structured Query Language 的所写,即是结构化查询语言。它用于管理关系数据库管理系统中的数据,如创建一个数据库、存储数据、读取数据、更新数据等。

关系数据库和关系数据库管理系统

关系数据库是指使用关系模型来组织数据的数据库,而关系数据数据库管理系统(RDBMS)则是用来管理关系数据库的一个软件系统。

常见的关系数据库管理系统有:

商用:微软的 SQL Server 和 Access,Oracle,IBM DB2 等。

开源:MySQL,PostgreSQL,SQLite,MariaDB 等。

非关系数据库

非关系数据库(NoSQL)是没有使用关系模型组织数据的数据库。和关系数据库使用行和列组成的表存储数据的方式不同,非关系数据库针对不同的数据的特点以不同的方式存储数据,如数据可以简单的存储为键值对、XML或者JSON等格式的文档、一个图等。

根据不同的数据模型(数据的组织方式),非关系数据数据管理系统大致可分为以下几类:

列式数据:Accumulo, Cassandra, Scylla, HBase.

文档数据:Apache CouchDB, ArangoDB, BaseX, Clusterpoint, Couchbase, Cosmos DB, IBM Domino, MarkLogic, MongoDB, OrientDB, Qizx, RethinkDB

键值对数据:Aerospike, Apache Ignite, ArangoDB, Berkeley DB, Couchbase, Dynamo, FoundationDB, InfinityDB, MemcacheDB, MUMPS, Oracle NoSQL Database, OrientDB, Redis, Riak, SciDB, SDBM/Flat File dbm, ZooKeeper

图数据:AllegroGraph, ArangoDB, InfiniteGraph, Apache Giraph, MarkLogic, Neo4J, OrientDB, Virtuoso

关系数据库和非关系数据库的比较

关系数据库:

优点 缺点
易于理解:结构化的数据存储(行列表) 采用固定的表结构,导致可扩展性查
便于操作:使用通用的 SQL 语言 读写性能较差,在大数据环境下更为明显
实现单表及多表的复杂查询

非关系数据库:

优点 缺点
数据存储格式多样、灵活,扩展性强 没有统一的数据管理语言,学习成本高
读写速度快 数据结构复杂,不支持类似多表的查询
部署和维护成本低

数据库管理的基本操作

操作环境:

Ubuntu-18.04 + MySQL

创建新用户

以 root 身份登陆 mysql:

1
sudo mysql -u root #同 sudo mysql

创建新用户:

1
2
3
4
5
6
7
mysql>
CREATE USER 'newuser'@'localhost' #@后面跟着的是主机名,可以是远程服务器:www.server.com
IDENTIFIED BY 'user-password';
GRANT INSERT,SELECT #用户的权限,这里分配了插入和选择缺陷,使用所有权限 ALL(不推荐)
ON *.* #全部数据库和表,可以指定数据库和表:database.* 或者 db.tablename
TO 'newuser'@'localhost'
WITH GRANT OPTION; #具有授于其它用户权限的能力,授予权限仅限于自己被授予的权限,一般不用该选项

更新授权表:

1
mysql> FLUSH PRIVILEGES; #是新用户的授权信息更新

查看数据库信息

在 MySQL 中查看,当前所有用户和l连接的主机和其密码

1
SELECT user,host,authentication_string FROM mysql.user # MySql 版本不同列名会有所区别

查看当前用户名:

1
SELECT user();

查看当前登陆当 MySQL 数据库服务器的用户:

1
SELECT user, host, db, command FROM information_schema.processlist;

查看所有数据库:

1
2
3
show DATABASES;
show DATABASSES LIKE “%s” #查看以 s 开头的数据库
show DATABASSES LIKE “s%” #查看以 s 结尾的数据库

查看数据库中所有表:

1
2
show TABLES FROM dbname LIKE "_[abc]%s"; 
show FULL TABLES; 查看所有的表,同时显示表类型(VIEW OR BASE TABLE)

查看表的信息:

1
desc table_name;

查看当前用户权限:

1
show GRANTS;

其它基本信息:

1
2
3
4
select @@version 	#MySQL 版本
select @@host #主机名
select @@database #当前数据库名
select @@dataaddr #MySQL文件目录

数据库操作

库操作

以新用户身份登陆 mysql:

1
sudo mysql -u newuser -p

创建一个数据库:

1
2
CREATE DATABASE dbname;
USE dbname; #选择该数据库

删除数据库:

1
DROP DATABASE dbname;

备份数据库:

1
BACKUP DATABASE databasename TO DISK = 'filepath';

表操作

创建一个表:

1
2
3
4
5
6
CREATE TABLE table_name (
column1 数据类型 [约束],
column2 数据类型 [约束],
column3 数据类型 [约束],
....
);

约束为可选项, SQL 约束 和 MySQL 数据类型见[附录](# 附录)。

例子:

1
2
3
4
5
CREATE TABLE tbname (
id int(255) NOT NULL AUTO_INCREMNET,
gender ENUM(male,female) NOT UNLL,
name varchar(255)
);

删除表:

1
DROP TABLE table_name;

修改表:

1
2
3
4
5
6
7
ALTER TABLE table_name ADD column_name datatype;  #增加一列
ALTER TABLE table_name DROP COLUMN column_name; #删除一列

#修改列的数据类型
ALTER TABLE table_name MODIFY COLUMN column_name datatype; #My SQL / Oracle (prior version 10G):
ALTER TABLE table_name MODIFY column_name datatype; #Oracle 10G and later
ALTER TABLE table_name ALTER COLUMN column_name datatype; #MS SQL Server / MS Access

数据操作

增加一条数据:

1
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

删除一条数据:

1
DELETE FROM table_name WHERE condition;

注意: 如果不带 WHERE 则会清空整张表的内容

例子: 从 Customers 表中删除 CustomerName 列值为 Alfreds Futterkiste 的行:

1
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

更改一条数据:

1
2
3
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

例子: 更改 Custmers 表中 CustmerID 列值为 1 的行中的数据, 修改 ContactName 和 City 列:

1
2
3
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

查找数据:

1
2
3
SELECT column1, column2, ...  #指定列名
FROM table_name
WHERE condition; #指定条件

查看表的所有数据:

1
SELECT * FROM tabel_name;

例子: 查找 Customers 表中所有符合 City 列值为 Berlin 的数据:

1
SELECT * FROM Customers WHERE City="Berlin";

参考资料

  1. Non-relational data and NoSQL
  2. 关系型数据库和非关系型数据的比较
  3. SQL Tutorial

附录

SQL 约束

约束 作用
NOT NULL 列值不能为空值
UNIQUE 列的值唯一
PRIMARY KEY 该列为主键, 主键的值不能为空且必须唯一, 每个表都必有且只有一个主键
FOREIGN KEY 该列为外键, 用于连接另一个表的主键
CHECK 约束列值的范围
DEFAULT 列的默认值
AUTO_INCREMENT ==MySQL 才是这样==, 每次添加新值时自动增加数值
INDEX 为列添加索引, 加快查找

例子(MySQL):

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int DEFAULT 0,
StudentID int,
PRIMARY KEY (ID),
INDEX name (LastName,FirstName),
CHECK(Age>=0),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

使用索引进行查询(MySQL):

1
select FisrstName FROM Persons USE INDEX(name);

MySQL 数据类型

字符串类型

常用 CHAR、VARCHAR

Data type Description
CHAR(size) A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes.
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT(size) Holds a string with a maximum length of 65,535 bytes
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(val1, val2, val3, …) A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them
SET(val1, val2, val3, …) A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list

数值型

常用 SMALLINT、INT、BOOL、FLOAT

Data type Description
BIT(size) A bit-value type. The number of bits per value is specified in size. The size*parameter can hold a value from 1 to 64. The default value for *size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255)
BOOL Zero is considered as false, nonzero values are considered as true.
BOOLEAN Equal to BOOL
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255)
MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255)
INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255)
INTEGER(size) Equal to INT(size)
BIGINT(size) A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255)
FLOAT(size, d) A floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will be removed in future MySQL versions
FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()
DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the dparameter
DOUBLE PRECISION(size, d)
DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the dparameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.
DEC(size, d) Equal to DECIMAL(size,d)

时间类型

常用 DATE,TIME,DATATIME

Data type Description
DATE A date. Format: YYYY-MM-DD. The supported range is from ‘1000-01-01’ to ‘9999-12-31’
DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time
TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch (‘1970-01-01 00:00:00’ UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from ‘-838:59:59’ to ‘838:59:59’
文章作者: BingSlient
文章链接: https://bingslient.github.io/2019/08/09/关系数据库管理基础/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 BingSlient's Blog
打赏
  • 微信
  • 支付寶