Database transactions, views, triggers, indexes, stored procedures, functions, three major paradigms

Transaction Transaction

A transaction is a logical set of operations on either perform or not to perform

Transaction Methods

  • Open transaction: start transaction
  • Commit the transaction: commit
  • Roll back the transaction: rollback

Characteristics of the transaction: ACID

  • Atomicity (Atomicity): operations in the transaction included, either execute successfully, or all fail.
  • Consistency (Consistency): The total number of database from a consistent state to another consistent state. (Total always remains the same)
  • Isolation (Isolation): operation of a transaction does not perform other transactions affecting internal data and operations, transactions concurrently executing independent of each other.
  • Persistent (Durability): After the transaction commits, changes to the data in the database is permanent and will not be lost due to a system crash.

State of concurrent transactions

  • Dirty read: when a transaction is accessing data, another transaction modifies this same data is submitted, prior to the transaction reads data modified, namely: "dirty data" .

Read a thread in the affairs of another update data in a transaction thread uncommitted.

  • Non-repeatable read: when a transaction is accessing data, another transaction modifies the data, after submitting, before the transaction reads data with different data before the modification.

Read a thread in the affairs of another data update in a transaction thread that have been submitted.

  • Waste (phantom read): When a transaction is accessing a table, the other data into a data transaction time before reading again, a more data than before.

A thread Affairs read a thread insert additional data transaction has been submitted.

Notes :

MySQL default isolation level: repeatable read

ORACLE default isolation level: read committed

Transaction isolation level inquiry

mysql 5
select @@session.tx_isolation;//查询当前会话事务隔离级别
select @@global.tx_isolation;//查询全局会话事务隔离级别

mysql 8
select @@session.transaction_isolation;//查询当前会话事务隔离级别
select@@global.transaction_isolation;//查询全局会话事务隔离级别
select @@transaction_isolation;//查询事务隔离级别

Set the transaction isolation level

set session transaction isolation level 隔离登记;

Transaction isolation level

  • read uncommitted (read uncommitted): lowest isolation level, allowing the read data changes have not been submitted, could lead to dirty reads, non-repeatable read, phantom read .
  • read committed (read committed): Allow Read committed data changes, anti-dirty read, but may also occur non-repeatable read, phantom read
  • repeatable read (Repeatable degrees): results of the same data read is always the same, unless the firm itself is modified. Otherwise the front end of the transaction, the data are the same, after the end of the transaction, the data read will change , anti-dirty reads, non-repeatable read, phantom read may still occur
  • Serializable (serializable): the highest isolation level, all transactions are sequentially executed one by one, it is impossible to produce interference between such transactions, low efficiency, can prevent dirty reads, non-repeatable read and phantom read .
Isolation Levels Dirty read Non-repeatable read Phantom read
READ-UNCOMMITTED
READ-COMMITTED ×
REPEATABLE-READ × ×
SERIALIZABLE × × ×

View View

create [algorithm = {undefined | merge | temptable}]
View 视图名
AS
select 查询语句

--删除视图
drop View 视图名;
  • algorithm A view selection algorithm.
  • undefined It means the automatic selection algorithm
  • merge Shows a view using the view definition statement combined, such that a partial view of a part of the statement corresponding substituted.
  • temptable It said it would view the results into a temporary table, then use the temporary table execute statement
  • with check optionWhen updating a view to ensure representation within the purview of the view.
    In simple terms it can be so explained: made by modifying the view, the view must be seen through the modified result.

Trigger Trigger

create trigger 触发器名
after/before insert/update/delete on 表名
for each row
begin
	sql语句;
end;

sql语句操作;

-- 删除触发器
drop trigger 触发器名;

Example:

create trigger tg4
after update on tbl_order
for each row
begin

 update goods set num = num + old.much-new.much where id= old.gid/new.gid;
end;

-- 会发现商品1的数量又变为8了
update tbl_order set much = 4 where oid= 4;
  • New: range: can be used in insert, update trigger
  • Old: Range: can be used in delete, update trigger

Index Index

CREATE TABLE table_name [col_name data type]
[unique|fulltext] [index|key] [index_name](col_name[length])[asc|desc]
  • unique | fulltext is optional, represent a unique index, full-text indexing
  • index and key are synonymous, both have the same effect, to create the specified index
  • index_name specifies the name of the index, is optional, if not specified, the default value for the index col_name
  • col_name create fields column index is desired, the column must be selected from a plurality of columns of the data defined in the table
  • optional length parameter indicating the length of the index, only the string type field to specify the length of the index
  • asc or desc specifies ascending or descending index value storage
#查看:
show indexes from `表名`;
#或
show keys from `表名`;
 
#删除
alter table `表名` drop index 索引名;

### general index

(1) directly create an index

CREATE INDEX index_name ON table_name(col_name);

Adding an index (2) modify the table structure

ALTER TABLE table_name ADD INDEX index_name(col_name);

(3) create a table when creating an index at the same time

CREATE TABLE `news` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `title` varchar(255)  NOT NULL ,
    `content` varchar(255)  NULL ,
    `time` varchar(20) NULL,
    PRIMARY KEY (`id`),
    INDEX index_name (title(255))
);


(4) delete the index

DROP INDEX index_name ON table_name;
或者
alter table `表名` drop index 索引名;

### composite index (combination index)

Composite Index: Composite index is an index created on multiple fields. Composite indexes to comply with "the most left-prefix" principle , namely the use of the composite index of the first field in the query, the index will be used . Therefore, the order in the composite index in the index column is essential.

(1) create a composite index

create index index_name on table_name(col_name1,col_name2,...);

The only index

Unique index: unique index and the ordinary index similar, the main difference is that a unique index limit values in the column must be unique, but allow null values (only allowed a null value) .

(1) create unique index

# 创建单个索引
CREATE UNIQUE INDEX index_name ON table_name(col_name);

# 创建多个索引
CREATE UNIQUE INDEX index_name on table_name(col_name,...);

(2) create table when the specified index directly

CREATE TABLE `news` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `title` varchar(255)  NOT NULL ,
    `content` varchar(255)  NULL ,
    `time` varchar(20) NULL DEFAULT NULL ,
    PRIMARY KEY (`id`),
    UNIQUE index_name_unique(title)
)


Primary key index

Primary key index is a special unique index, a table can have only one primary key, does not allow nulls. Usually at the same time create a primary key index when construction of the table:

(1) primary key index (added when creating a table)

CREATE TABLE `news` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `title` varchar(255)  NOT NULL ,
    `content` varchar(255)  NULL ,
    `time` varchar(20) NULL DEFAULT NULL ,
    PRIMARY KEY (`id`)
)

Full-text index

Create a table for adding full-text index

CREATE TABLE `news` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `title` varchar(255)  NOT NULL ,
    `content` text  NOT NULL ,
    `time` varchar(20) NULL DEFAULT NULL ,
     PRIMARY KEY (`id`),
    FULLTEXT (content)
)


(2) create an index directly

CREATE FULLTEXT INDEX index_fulltext_content ON table_name(col_name)

Stored Procedures

A stored procedure is a set of programmable functions, in order to accomplish a specific set of SQL statements, users can assign parameters and to be called by the name of the stored procedure execution.

Create a stored procedure

create procedure 过程名(in/out/inout 参数名 参数类型)
begin
	sql语句 --> 一段业务逻辑
	可用sql语法
end;
create procedure demo_inout_parameter(inout p_inout int)
begin
 select p_inout;
 set p_inout=2;
 select p_inout;
end;

-- 调用存储过程
set @p_inout=1;
call demo_inout_parameter(@p_inout);
select @p_inout;

drop procedure 存储过程名

The IN : parameter values may change during storage ( SET ), a variable name to select values of the parameters. The parameter value can not be returned.

OUT : parameter values may change during storage, and returns

INOUT : When calling specified and may be changed and returned

function

 -- 如果有这个函数,就删除
drop function if exists 函数名;

-- 创建一个无参的函数
create function hello () 
 -- 设置函数的返回类型
returns 参数类型,如:varchar (255)
begin-- 函数头
    -- 中间的是函数体
    return '一个简单的mysql函数'; -- 函数的返回值
end; -- 函数结尾

--调用函数
select hello();   -- select 函数名

The difference between stored procedures and functions

  • Essentially no difference, only the function returns a single value or a table object by return statement

    Stored procedure does not allow return, but can return out through a plurality of parameter values

    Function can be used in embedded SQL can select the call; not stored procedure

  • Function only in the type of stored procedure in / out / inout type

Three Forms Database

  • The first paradigm : Let R when all the attributes are not decomposed at a more basic data unit, said R satisfies the first paradigm is abbreviated as 1NF.

    ** ** column can not be divided required attribute is atomic, no longer decomposition;

  • The second paradigm : If the first normal form relational schema R and R have all non-primary attributes are totally dependent on the properties of each of the candidate key of R, R, said second normal, abbreviated as 2NF. Namely: a table can only preserve a data, can not put a variety of data stored in the same database table

    Meet paradigm about, non-primary attributes entirely dependent on the code, eliminate partially dependent.

  • Third Pattern : Let R be a relational model of the first condition is satisfied Paradigm, R X is an arbitrary set of properties, if X is dependent on non-transmission of one candidate keyword any R, R satisfies said third paradigm, referred to simply as 3NF . each column data are directly related to the primary key and, while not directly related.

    For example, there is a department information table, where each department has a department number (dept_id), department name, department briefings and other information. Then list the department number after the employee information table can no longer with the department information about the department name, department, etc. About adding staff information table .

    Satisfy the two paradigms, eliminating dependence transfer

Published 12 original articles · won praise 0 · Views 54

Guess you like

Origin blog.csdn.net/DavinDeng/article/details/104918585