Database - the relational model and SQL

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Relational model and SQL

  1. Mysql database with the following example to introduce the relational model

installation

MariaDB installation

yum list | grep mariadb #查看

yum install mariadb-server #安装

systemctl start mariadb.server #启动

ss -tanl #查看状态, 确认启动成功
State    Recv-Q   Send-Q   Local Address:Port   Peer Address:Port
LISTEN   0        50                 *:3306                *:*

systemctl enable mariadb.server #设置开机启动

mysql_secure_installation #进行安全设置

mysql -u root -p < test.sql #导入测试版本
mysql -u root -p < scripts/mysql.sql #在gogs目录下执行, 就是创建了gogs库

mysql -u root -p #数据库root账户密码登录

show databases; #列出所有库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

grant all on *.* to '用户名'@'%' identified by '密码'; #创建并授权用户(*.*:权限范围, 本命令中的权限是所有库所有文件)

flush privileges; #刷新

SQL statements

SQL is Structured Query Language Structured Query Language. Organization for Standardization ISO 1987
supports all major relational database SQL, NoSQL is also a large part of SQL support

SQL statements are divided into:

  1. Data definition language, is responsible for the database definition, database objects defined by CREATE, DROP and three kinds of statements.
  2. DML Data Manipulation Language, responsible for the operation of the database objects, CRUD CRUD
  3. DCL Data Control Language, is responsible for database access control by GRANT and REVOKE commands consisting of two
  4. TCL Transaction Control Language, responsible for ACID transactions, support commit, rollback instructions

Language Specification:

  1. SQL statements are not case sensitive
    1. General recommendations, SQL keywords, functions, and so capital
  2. SQL statements should end with the end semicolon
  3. Note
    1. Multi-line comments / footnotes /
    2. Single-line comments - the comment content
    3. MySQL can use annotation #
  4. Use spaces or indentation to improve readability
  5. Naming conventions
    1. We must begin with a letter
    2. You can use numbers, #, $, and _
    3. Do not use keywords

DCL

GRANT authorization, REVOKE revoked

GRANT ALL ON employees.* TO 'wayne'@'%' IDENTIFIED by 'wayne';
REVOKE ALL ON *.* FROM wayne;

* 为通配符,指代任意库或者任意表。 *.* 所有库的所有表; employees.* 表示employees库下所有的表
% 为通配符,它是SQL语句的通配符,匹配任意长度字符串

DDL

Delete User (caution)

DROP USER wayne;

Creating a database
library is a collection of data, all data according to the data model in the database organization

CREATE DATABASE IF NOT EXISTS test CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE IF NOT EXISTS test CHARACTER SET utf8;

CHARACTER SET charset
utf8mb4 utf8 is extended, support utf8mb4 4 bytes, needed MySQL5.5.3 +
collation COLLATE designated character set, a character string for comparison. For example a, A big Who?

Delete Database

DROP DATABASE IF EXISTS gogs;

Create table
table is divided into rows and columns, MySQL database is kept row. Data are stored line by line, how many columns are to be fixed column
line Row, also referred to as recording Record, tuples
column Column, also called fields Field, Attribute
range field called domain Domain. For example, the value M is gender field values or two F
! [Image]

CREATE TABLE `employees` (
 `emp_no` int(11) NOT NULL,
 `birth_date` date NOT NULL,
 `first_name` varchar(14) NOT NULL,
 `last_name` varchar(16) NOT NULL,
 `gender` enum('M','F') NOT NULL,
 `hire_date` date NOT NULL,
 PRIMARY KEY (`emp_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The name of anti-quotation marks, will be considered non-keyword, use backticks to avoid conflict

DESC

See column information
{DESCRIBE | DESC} tbl_name [col_name | wild]

DESC employees;
DESC employees '%name';

relationship

In a relational database, the relationship is a two-dimensional tables of rows and columns

Row Row, also referred to as recording Record, tuples
column Column, also called fields Field, Attribute
range field called domain Domain. E.g. gender field value is M or two values F

Dimension: Relationship between the dimension of the relationship refers to the number of attributes in
the base: the number of tuples

Note that in a relationship, the order of attributes is not important. In theory, the tuple order is not important, but because of the order of tuples associated with the storage, it will affect query efficiency

Candidate key

Relationship, that uniquely identifies the attribute or set of attributes from a tuple, referred to as candidate keys

PRIMARY KEY primary key

A table or a plurality of columns of unique key, that is, through the one or more columns that uniquely identifies a record. I.e. the selected candidate key

Primary key can not contain a null value null. The primary key is often set to an integer, long integer, can be increased from the field AUTO_INCREMENT

Primary key table can not, however, the general design of the table, will often have a primary key, in order to avoid duplicate recording

Foreign KEY foreign key

Strictly speaking, when an attribute or set of attributes in a relationship with another relation (which may be itself) the candidate key match, the attribute or set of attributes called a foreign key

Index Index

Can be seen as a dictionary catalog, used for fast retrieval. Space for time, significantly improve query efficiency

Index may be set to a plurality of columns or fields

Primary key index, primary key will automatically create a primary key index, primary key itself is to quickly locate the only record of

Unique index, the index table of the index columns must be unique, but it can be empty, non-empty value must be unique

The general index, there is no uniqueness requirement is to build a dictionary of the directory only

In MySQL, InnoDB MyISAM and the index data structure may be used BTree or Hash, the default is BTree

Hash time complexity is O (1), but only an exact match, that is, matching Hash values, such as range matches no other way, hash values ​​can not know the disorder so the order of the original recording. Hash many problems

BTree indexes to a B + tree structure for storage

Although the index can improve query read, but additions and deletions affect the efficiency of the index because of the need to update or remodeling. Frequently appear in the where clause columns can consider using the index. To avoid this field is set gender index

Constraints Constraint

In order to ensure complete and accurate data, the data model must also support the integrity constraints

"Must have value" constraint
values of some column must have a value, not allowed to be empty NULL

Domain Constraints Domain Constraint

Defining a range of fields in table

Entity integrity Entity Integrity

PRIMARY KEY constraint defines the primary key, the primary key constraint definition. Will not be repeated and only the primary key, can not be empty

Referential integrity Referential Integrity ***

Foreign key definition, you can not reference another table's primary key, however, is often cited concern only the actual primary key

Foreign keys: a column in Table B, the primary key referenced in Table A, Table B is a foreign key column

A table is called the primary table, B table is called from the table

  1. Insert a rule
    need not be specified

If a record is inserted in the table B, the foreign key column is inserted a B value, this value must be the primary key table present in A

  1. Update rule
    specifies the rules define the foreign key constraint
  2. Delete rules
    specify that the rule defining foreign key constraint

Foreign key constraint operation

Setpoint Explanation
CASCADE Cascade automatically delete or update a parent table deletes or updates from the child table match rows
SET NULL Delete or update the parent table row, will set the foreign key in the child table as NULL, but must ensure that the child table column is not specified NOT NULL, that is to say from the sub-fields of the table can be NULL job
RESTRICT If you remove the primary key from the parent table, if the child table references, delete or update operation is rejected on the parent table
No ACTION Standard SQL keywords in MySQL and RESTRICT same. He refused to delete or update operation for the parent table

Foreign key constraint, in order to ensure data integrity, consistency, eliminate the number of redundant data error

Entity - Contact ER

The establishment of a database, we need to collect user requirements, designed to meet the requirements of the enterprise data model. The construction of this model requires method, this method needs to be ER Entity - Relationship Modeling. There have been a modeling language --UML (Unified Modeling Language) Unified Modeling Language

Entity Entity: a set of real-world objects with the same properties, may be things or abstract things physically present

Contact Relationship: a collection of associations between entities

Contact type entities

Types of description solution
Many Contact 1: n An employee belongs to a department, a department has multiple employees Foreign key employees; the primary key sectors
Contact-many m: n Employees belonging to a number of departments, a department has multiple employees Establishing a third table
One on one contact 1: 1 Suppose entity manager, a manager managing a department, a department has only one manager Field construction in which tables are OK

One relationship with the less often represents a unique association of Table A Table records a record B, and vice versa

It is often a table in order to produce multi-column split and become more than one table, together complete information, or to facilitate inquiries, or for data security isolation

Part of the data field and the like

view

View, also known as virtual table that looks like a table. It is generated by the query statement. CRUD operations may be performed through a view

View of the role

  1. Streamline operations, complex query SQL statement is defined as a view, you can simplify the query

  2. Data security, the view to show only some of the columns of the real table, or calculated results, thus hiding the real table

type of data

MySQL data types

Types of meaning
tinyint 1 byte signed range -128 to 127. Unsigned range is 0 to 255. bool or boolean, is tinyint, 0 for false and non-zero real
smallint 2-byte, unsigned range is -32768 to 32767. Unsigned range is 0 to 65535
int Integer 4 bytes, with Integer, the range -2147483648 to be signed 2147483647. Unsigned range is 0 to 4,294,967,295
bigint Long, 8 bytes, the range is signed to -9223372036854775808 9223372036854775807. Unsigned range is 0-18446744073709551615
float Single-precision floating-point accurate to approximately 7 decimal places
double Double-precision floating-point accurate to approximately 15 decimal
DATE date. Supported range '1000-01-01' to '9999-12-31'
DATETIME Support range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP Timestamp. Range is '1970-01-01 00:00:00' to 2037
char(M) Fixed length, filled to the right with spaces to the length requirements. M is the length, in the range of 0 to 255. M refers to the number of characters
varchar(M) Variable-length strings. M represents the maximum length of the column. M range is 0 to 65,535. But can not break through the line of maximum number of bytes 65535
text Large text. The maximum length is 65535 (2 ^ 16-1) characters.
BLOB Large bytes. The maximum length is 65535 (2 ^ 16-1) bytes BLOB column

LENGTH function returns the number of bytes. The char and varchar is defined by M character limit

char string may be defined as a fixed length, space for time, slightly higher efficiency; VARCHAR variable-length, saving space

Relational Operations

Relationship: In a relational database, the relationship is a two-dimensional table
relations operation that operations on the table

Selection (selection): also known limits, is selected to satisfy a given condition from the relationship tuple

A projection (projection): in the relationship between the projection column is selected from a number of attributes to form new relations

Connect (join): to connect two different relationships into a relationship

DML - CRUD CRUD

nsert statement

INSERT INTO table_name (col_name,...) VALUES (value1,...);
-- 向表中插入一行数据,自增字段、缺省值字段、可为空字段可以不写

INSERT INTO table_name SELECT ... ;
-- 将select查询的结果插入到表中

INSERT INTO table_name (col_name1,...) VALUES (value1,...) ON DUPLICATE KEY UPDATE col_name1=value1,...;
-- 如果主键冲突、唯一键冲突就执行update后的设置。这条语句的意思,就是主键不在新增记录,主键在就更新部分字段

INSERT IGNORE INTO table_name (col_name,...) VALUES (value1,...);
-- 如果主键冲突、唯一键冲突就忽略错误,返回一个警告


INSERT INTO reg (loginname, `name`, `password`) VALUES ('tom', 'tom', 'tom');
INSERT INTO reg (id, loginname, `name`, `password`) VALUES (5, 'tom', 'tom', 'tom');
INSERT INTO reg (id, loginname, `name`, `password`) VALUES (1, 'tom', 'tom', 'tom') ON DUPLICATE KEY UPDATE name = 'jerry';

Update statement

UPDATE [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition]
-- IGNORE 意义同Insert语句

UPDATE reg SET name='张三' WHERE id=5;


-- 注意这一句非常危险,会更新所有数据
UPDATE reg SET name = 'ben';

-- 更新一定要加条件
UPDATE reg SET name = 'ben', password = 'benpwd' WHERE id = 1;

Delete Statement

DELETE FROM tbl_name [WHERE where_definition]
-- 删除符合条件的记录

-- 删除一定要有条件
DELETE FROM reg WHERE id = 1;

Select Statement

SELECT
    [DISTINCT]
    select_expr, ...
    [FROM table_references
    [WHERE where_definition]
    [GROUP BY {col_name | expr | position}
        [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_definition]
    [ORDER BY {col_name | expr | position}
        [ASC | DESC] , ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [FOR UPDATE | LOCK IN SHARE MODE]]

FOR UPDATE rows will write lock, this is an exclusive lock

Query
result of the query result set to become recordset

SELECT 1;

-- 最简单的查询
SELECT * FROM employees;

-- 字符串合并
SELECT emp_no, first_name + last_name FROM employees;
SELECT emp_no, CONCAT(first_name,' ',last_name) FROM employees;

-- AS 定义别名,可选。写AS是一个好习惯
SELECT emp_no as `no`, CONCAT(first_name,' ',last_name) name FROM employees emp;

Limit clause

-- 返回5条记录
SELECT * FROM employees emp LIMIT 5;

-- 返回5条记录,偏移18条
SELECT * FROM employees emp LIMIT 5 OFFSET 18;
SELECT * FROM employees emp LIMIT 18, 5;

Where clause

Operators description
= equal
<> not equal to
>、<、>=、<= Greater than, less than, greater than or equal, less than or equal
BETWEEN Within a certain range, between a and b is equivalent to [a, b]
LIKE String pattern matching,% represents any number of characters, a character represented _
IN Specify the possible values ​​for a plurality of columns
AND versus
OR or

Note: If you need to use a lot of expression values ​​AND, OR computing logical expression, because of a problem with the associative law, it is recommended to use parentheses to avoid errors

-- 条件查询
SELECT * FROM employees WHERE emp_no < 10015 and last_name LIKE 'P%';
SELECT * FROM employees WHERE emp_no BETWEEN 10010 AND 10015 AND last_name LIKE 'P%';
SELECT * FROM employees WHERE emp_no in (10001, 10002, 10010);

Order by clause

Sort query results, can be ascending ASC, DESC descending order

-- 降序
SELECT * FROM employees WHERE emp_no in (10001, 10002, 10010) ORDER BY emp_no DESC;

DISTINCT

Does not return duplicate records

-- DISTINCT使用
SELECT DISTINCT dept_no from dept_emp;
SELECT DISTINCT emp_no from dept_emp;
SELECT DISTINCT dept_no, emp_no from dept_emp;

Aggregate function

function description
COUNT(expr) Returns the number of rows recorded in the recording, if the columns are specified, return non-NULL values
COUNT(DISTINCT expr,[expr…]) Returns non-NULL value will not be repeated the number of rows
AVG([DISTINCT] expr) Returns the average, the average return different values
MIN (expr), MAX (expr) Minimum, maximum,
SUM([DISTINCT] expr) Sum, Distinct return different values ​​sum
-- 聚合函数SELECT COUNT(*), AVG(emp_no), SUM(emp_no), MIN(emp_no), MAX(emp_no) FROM employees;

Grouping queries

Group by using clause, if the conditions, using the results Having clause to filter packets, the polymerized

-- 聚合所有
SELECT emp_no, SUM(salary), AVG(salary), COUNT(emp_no) from salaries;
-- 聚合被选择的记录
SELECT emp_no, SUM(salary), AVG(salary), COUNT(emp_no) from salaries WHERE emp_no < 10003;

-- 分组
SELECT emp_no FROM salaries GROUP BY emp_no;
SELECT emp_no FROM salaries WHERE emp_no < 10003 GROUP BY emp_no;

-- 按照不同emp_no分组,每组分别聚合
SELECT emp_no, SUM(salary), AVG(salary), COUNT(emp_no) from salaries WHERE emp_no < 10003 GROUP BY emp_no;

-- HAVING子句对分组结果过滤
SELECT emp_no, SUM(salary), AVG(salary), COUNT(emp_no) from salaries GROUP BY emp_no HAVING AVG(salary) > 45000;

-- 使用别名
SELECT emp_no, SUM(salary), AVG(salary) AS sal_avg, COUNT(emp_no) from salaries GROUP BY emp_no HAVING sal_avg > 60000;

-- 最后对分组过滤后的结果排序
SELECT emp_no, SUM(salary), AVG(salary) AS sal_avg, COUNT(emp_no) from salaries GROUP BY emp_no HAVING sal_avg > 60000 ORDER BY sal_avg;

分组是将数据按照指定的字段分组,最终每组只能出来一条记录。这就带来了问题,每一组谁做代表,其实谁做代表都不合适
如果只投影分组字段、聚合数据,不会有问题,如果投影非分组字段,显示的时候不能确定是组内谁的数据

-- 分组
SELECT emp_no, MAX(salary) FROM salaries; -- 10001 88958
SELECT emp_no, MIN(salary) FROM salaries; -- 10001 40006

上例很好的说明了使用了聚合函数,虽然没有显式使用Group By语句,但是其实就是把所有记录当做一组,每组只能出一条,那么一组也只能出一条,所以结果就一条
但是emp_no就是非分组字段,那么它就要开始覆盖,所以,显示为10001。当求最大值的时候,正好工资表中10001的工资最高,感觉是对的。但是,求最小工资的时候,明明最小工资是10003的40006,由于emp_no不是分组字段,导致最后被覆盖为10001

SELECT emp_no, MIN(salary) FROM salaries GROUP BY emp_no;

上句才是正确的语义,按照不同员工emp_no工号分组,每一个人一组,每一个人有多个工资记录,按时每组只能按照人头出一条记录

-- 单表较为复杂的语句
SELECT
    emp_no,
    avg(salary) AS avg_salary
FROM
    salaries
WHERE
    salary > 70000
GROUP BY
    emp_no
HAVING
    avg(salary) > 50000
ORDER BY
    avg_salary DESC
LIMIT 1;

子查询

查询语句可以嵌套,内部查询就是子查询
子查询必须在一组小括号中
子查询中不能使用Order by

-- 子查询
SELECT * FROM employees WHERE emp_no in (SELECT emp_no from employees WHERE emp_no > 10015) ORDER BY emp_no DESC;
SELECT emp.emp_no, emp.first_name, gender FROM (SELECT * from employees WHERE emp_no > 10015) AS emp WHERE emp.emp_no < 10019 ORDER BY emp_no DESC;

连接Join

交叉连接cross join
笛卡尔乘积,全部交叉
在MySQL中,CROSS JOIN从语法上说与INNER JOIN等同

Join会构建一张临时表

-- 工资40行
SELECT * FROM salaries;

-- 20行
SELECT * FROM employees;

-- 800行
SELECT * from employees CROSS JOIN salaries;

-- 隐式连接,800行
SELECT * FROM employees, salaries;

注意:salaries和employees并没有直接的关系,做笛卡尔乘积只是为了看的清楚

  1. 内连接
    inner join,省略为join
    等值连接,只选某些field相等的元组(行),使用On限定关联的结果
    自然连接,特殊的等值连接,会去掉重复的列。用的少
-- 内连接,笛卡尔乘积 800行
SELECT * from employees JOIN salaries;
SELECT * from employees INNER JOIN salaries;

-- ON等值连接 40行
SELECT * from employees JOIN salaries ON employees.emp_no = salaries.emp_no;

-- 自然连接,去掉了重复列,且自行使用employees.emp_no = salaries.emp_no的条件
SELECT * from employees NATURAL JOIN salaries;
  1. 外连接
    outer join,可以省略为join
    分为左外连接,即左连接;右外连接,即右连接;全外连接
-- 左连接
SELECT * from employees LEFT JOIN salaries ON employees.emp_no = salaries.emp_no;
-- 右连接
SELECT * from employees RIGHT JOIN salaries ON employees.emp_no = salaries.emp_no;
-- 这个右连接等价于上面的左连接
SELECT * from salaries RIGHT JOIN employees ON employees.emp_no = salaries.emp_no;

左外连接、右外连接
SELECT * from employees RIGHT JOIN salaries ON employees.emp_no = salaries.emp_no;
结果是先employees后salaries的字段显示,Right是看表的数据的方向,从salaries往employees看,以salaries为准,它的所有数据都显示

  1. 自连接
    表,自己和自己连接
select manager.* from emp manager,emp worker where manaer.empno=worker.mgr and worker.empno=1;
select manager.* from emp manager inner join emp worker on manaer.empno=worker.mgr where worker.empno=1;

存储过程、触发器

存储过程(Stored Procedure),数据库系统中,一段完成特定功能的SQL语句。编写成类似函数的方式,可以传参并调用。支持流程控制语句

触发器(Trigger),由事件触发的特殊的存储过程,例如insert数据时触发

这两种技术,虽然是数据库高级内容,性能不错,但基本很少用了;它们移植性差,使用时占用的服务器资源,排错、维护不方便
最大的原因,不太建议把逻辑放在数据库中

事务Transaction

InnoDB引擎,支持事务
事务,由若干条语句组成的,指的是要做的一系列操作

关系型数据库中支持事务,必须支持其四个属性(ACID):

特性 描述
原子性(atomicity) 一个事务是一个不可分割的工作单位,事务中包括的所有操作要么全部做完,要么什么都不做
一致性(consistency) 事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的
隔离性 (isolation) 一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰
持久性(durability) 持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响
  1. 原子性,要求事务中的所有操作,不可分割,不能做了一部分操作,还剩一部分操作
  2. 一致性,多个事务并行执行的结果,应该和事务排队执行的结果一致。如果事务的并行执行和多线程读写共
  3. 享资源一样不可预期,就不能保证一致性
  4. 隔离性,就是指多个事务访问共同的数据了,应该互不干扰。隔离性,指的是究竟在一个事务处理期间,其他事务能不能访问的问题
  5. 持久性,比较好理解,就是事务提交后,数据不能丢失

MySQL隔离级别

隔离性不好,事务的操作就会互相影响,带来不同严重程度的后果

首先看看隔离性不好,带来哪些问题:

  1. 更新丢失Lost Update
    事务A和B,更新同一个数据,它们都读取了初始值100,A要减10,B要加100,A减去10后更新为90,B加100更新为200,A的更新丢失了,就像从来没有减过10一样
  2. 脏读
    事务A和B,事务B读取到了事务A未提交的数据(这个数据可能是一个中间值,也可能事务A后来回滚事务)。事务A是否最后提交并不关心。只要读取到了这个被修改的数据就是脏读
  3. 不可重复读Unrepeatable read
    事务A在事务执行中相同查询语句,得到了不同的结果,不能保证同一条查询语句重复读相同的结果就是不可以重复读
    例如,事务A查询了一次后,事务B修改了数据,事务A又查询了一次,发现数据不一致了
    注意,脏读讲的是可以读到相同的数据的,但是读取的是一个未提交的数据,而不是提交的最终结果
  4. 幻读Phantom read
    事务A中同一个查询要进行多次,事务B插入数据,导致A返回不同的结果集,如同幻觉,就是幻读
    数据集有记录增加了,可以看做是增加了记录的不可重复读

有了上述问题,数据库就必须要解决,提出了隔离级别
隔离级别由低到高,如下表

隔离级别 描述
READ UNCOMMITTED 读取到未提交的数据
READ COMMITTED 读已经提交的数据,ORACLE默认隔离级别
REPEATABLE READ 可以重复读,MySQL的 默认隔离级别
SERIALIZABLE 可串行化。事务间完全隔离,事务不能并发,只能串行执行

隔离级别越高,串行化越高,数据库执行效率低;隔离级别越低,并行度越高,性能越高
隔离级别越高,当前事务处理的中间结果对其它事务不可见程度越高

-- 设置会话级或者全局隔离级别
SET [SESSION | GLOBAL] TRANSACTION ISOLATION LEVEL
{READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE}


-- 查询隔离级别
SELECT @@global.tx_isolation;
SELECT @@tx_isolation;

SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;


-- 禁用自动提交
SET AUTOCOMMIT = 0

SERIALIZABLE,串行了,解决所有问题
REPEATABLE READ,事务A中同一条查询语句返回同样的结果,就是可以重复读数据了。例如语句为(select * from user)。解决的办法有:

  1. 对select的数据加锁,不允许其它事务删除、修改的操作
  2. 第一次select的时候,对最后一次确切提交的事务的结果做快照

解决了不可以重复读,但是有可能出现幻读。因为另一个事务可以增删数据

READ COMMITTED,在事务中,每次select可以读取到别的事务刚提交成功的新的数据。因为读到的是提交后的数据,解决了脏读,但是不能解决 不可重复读 和 幻读 的问题。因为其他事务前后修改了数据或增删了数据

READ UNCOMMITTED,能读取到别的事务还没有提交的数据,完全没有隔离性可言,出现了脏读,当前其他问题
都可能出现

事务语法

START TRANSACTION or BEGIN begin a transaction, START TRANSACTION is standard SQL syntax
using the COMMIT transaction commits, its changes permanent
ROLLBACK can before committing the transaction, rollback change operations in a transaction like the same did not happen (atomic)
SET AUTOCOMMIT statement disables or enables the default autocommit mode for the current connection. SET AUTOCOMMIT = 0 to disable automatic commit the transaction. If you enable auto-commit, if there is a statement after the implementation of changes to the table, the update will be stored to disk immediately

The difference between the data warehouse and database

It is not the essential difference, where data are stored, but persistent concerns database data, relational data, supporting business systems, transaction support; data warehouse storing the data in order to analyze or explore the design table structure, you can store huge amounts of data

Online transaction data stored in the database OLTP (online transaction processing OLTP, On-line Transaction Processing) ; a data warehouse to store historical data
for analysis OLAP (online analytical processing OLAP, On-Line Analytical Processing)

Database support online business requires frequent additions and deletions; general hoarding data warehouse of historical data for analysis of SQL support is generally not recommended deletion

Other concepts

Cursor Cursor

A method of operating a query result set
can move the cursor as a pointer to a row in the result set

Guess you like

Origin blog.csdn.net/weixin_44800244/article/details/95018925