MySQL database advanced articles_view, transaction, index

Advanced MySQL Database

view

For complex query SQL statements, it is often obtained by multiple tables for related queries. If the database changes due to requirements and other reasons, in order to ensure that the query data is the same as before, it needs to be modified in multiple places, and maintenance is very troublesome, this time we can by 定义视图way of to resolve.

What is a view?

通俗一点来说,'视图' 其实就是一个 'SELECT' 语句的结果集。So when we were in 使用视图, the main job was to create this SQL query.

视图的本质是对若干个基本表/引用表的引用,一张虚表(也可以理解为假的表),查询语句执行的结果, In fact, the actual data is not stored (when the basic table/reference table data changes, the result of the query execution of the view will also change).

视图The advantage is that query operations, reduce complex SQL statements, and enhance readability.

Define the view

  • It is recommended that the view name starts with'v_'
create view 视图名称 as select语句;

View attempt

  • The view table will also list all the views
show tables;

Use view

  • The purpose of the view is to query
select * from v_stu_score;

Delete view

  • drop view view name;
drop view v_stu_sco;

View Demo

view01

view02

view03

view04

The role of the view

  • Improved reusability, just like a function
  • Refactor the database without affecting the operation of the program
  • Improved security performance, can be used for different users
  • Make the data clearer

一般大公司有自己的数据库设计规范,比如禁止使用视图之类的情况。

Affairs

What is a transaction?

The transaction is widely used in various scenarios such as order system, banking system, etc.

例如:

	A用户和B用户是银行的储户,现在A要给B转账500元,那么需要做以下几件事:

		1、检查A的账户余额>500元;
		2、A 账户中扣除500元;
		3、B 账户中增加500元;

The normal process went down, A account deducted 500, B account added 500, everyone is happy.

What if the system fails after the money is deducted from account A? A lost 500 in vain, and B did not receive the 500 that should have belonged to him.

In the above case, a prerequisite is hidden: A deducts money and B increases money, either succeeds at the same time, or fails at the same time. This is the need for transactions

所谓事务,它是一个操作序列,这些操作要么都执行,要么都不执行,它是一个不可分割的工作单位。

For example, bank transfer work: deducting money from one account and adding money to another account, these two operations are either performed or not performed. Therefore, they should be regarded as a matter. A transaction is a unit for the database to maintain data consistency. At the end of each transaction, data consistency can be maintained.

Four characteristics of transactions (ACID for short)

  • Atomicity
  • Consistency
  • Isolation
  • Durability

The following content is from the third edition of "High Performance MySQL". Understanding the ACID of transactions and the four isolation levels helps us better understand transaction operations.

The following is a classic example of a banking application that explains the necessity of transactions. Suppose a bank’s database has two tables: checking and savings. Now to transfer $200 from user Jane’s checking account to her savings account, at least three steps are required:

Check that the balance of the checking account is greater than or equal to $200.
Subtract $200 from the checking account balance.
Add 200 dollars to the savings account balance.

上述三个步骤的操作必须打包在一个事务中,任何一个步骤失败,则必须回滚所有的步骤。

You can start a transaction with the START TRANSACTION statement, and then either use COMMIT to commit the modified data to persist, or use ROLLBACK to undo all modifications. The sample of transaction SQL is as follows:

1、start transaction;
2、select balance from checking where customer_id = 10233276;
3、update checking set balance = balance - 200.00 where customer_id = 10233276;
4、update savings set balance = balance + 200.00 where customer_id = 10233276;
5、commit;

A good transaction processing system must have these standard features

  • Atomicity

A transaction must be regarded as an indivisible minimum unit of work. All operations in the entire transaction are either submitted successfully or all failed and rolled back. For a transaction, it is impossible to perform only part of the operations. This is the transaction Atomicity

  • Consistency

The database always transitions from one consistent state to another consistent state. (In the previous example, consistency is ensured. Even if the system crashes between the execution of the third and fourth statements, there will be no loss of $200 in the checking account, because the transaction is not finally committed, so the changes made in the transaction are also Will not be saved to the database.)

  • Isolation

Generally speaking, changes made by one firm are not visible to other transactions until they are finally submitted. (In the previous example, when the third statement is executed and the fourth statement has not yet started, another account summary program is running at this time, and it sees that the balance of the checking account has not been subtracted by 200 US dollars.)

  • Durability

Once the transaction is committed, its changes will be permanently saved to the database. (At this time, even if the system crashes, the modified data will not be lost.)

Transaction order

  • The engine type of the table must be of innodb type to use transactions, which is the default engine for mysql tables.

View the creation statement of the table, you can see engine=innodb

-- 选择数据库
use jing_dong;
-- 查看goods表
show create table goods;

To open the transaction, the command is as follows:

  • Execute the modification command after opening the transaction, the changes will be maintained in the local cache, but not in the physical table
begin;
或者
start transaction;

Commit the transaction, the command is as follows

  • Maintain the data changes in the cache to the physical table
commit;

To roll back the transaction, the command is as follows:

  • Discard the changed data in the cache
rollback;

note

  • The command to modify the data will automatically trigger the transaction, including insert, update, delete
  • The reason for manually opening the transaction in the SQL statement is: you can modify the data multiple times, if it succeeds together, it will roll to the previous data together.

index

The ratio of reading and writing of general application system to database is about 10:1 (that is, there is 1 write operation when there are 10 query operations), and there are few performance problems in insert operations and update operations, and they encounter the most and most easily The problem is still some complex query operations, so the optimization of the query statement is obviously the top priority.

When the amount of data in the database is very large, it will become very slow to find the data, this time it will be used优化解决方案:索引。

What is an index?

Indexes are a special type of file (the index on the InnoDB data table is an integral part of the table space), they contain reference pointers to all records in the data table.

More generally speaking, the database index is like a table of contents in front of a book, which can speed up the query speed of the database.

The purpose of the index

The purpose of indexing is to improve query efficiency. It can be compared to a dictionary. If we want to look up the word "mysql", we must locate the m letter, then find the y letter from the bottom, and then find the rest of the sql. If there is no index, then you may need to look through all the words to find what you want. What if I want to find the word beginning with m? Or the words beginning with ze? Do you think that this thing can't be done without indexing?

Principle of Index

In addition to dictionaries, examples of indexes can be found everywhere in life, such as train schedules at train stations and catalogs of books. Their principle is the same. By constantly narrowing down the range of data you want to obtain, you can filter out the final desired result, and at the same time turn random events into sequential events, that is, we always lock through the same search method. data.

The database is the same, but it is obviously much more complicated, because it is not only faced with equivalent queries, but also range queries (>, <, between, in), fuzzy queries (like), union queries (or), and so on. What way should the database choose to deal with all the problems? Let us recall the example of a dictionary. Can we divide the data into segments and then query them in segments? The simplest one is if 1000 pieces of data, 1 to 100 are divided into the first paragraph, 101 to 200 are divided into the second paragraph, and 201 to 300 are divided into the third paragraph... In this way, to check the 250th piece of data, only the third paragraph is enough. Removed 90% of invalid data.

suoyin01

Use of index

  • View index
show index from 表名;
  • Create index
    • If the specified field is a string, the length needs to be specified, and it is recommended that the length be the same as the length when the field was defined
    • If the field type is not a string, you don’t need to fill in the length part
create index 索引名称 on 表名(字段名称(长度))
  • Delete index
drop index 索引名称 on 表名;

Index Demo

Create test table testindex

create table test_index(title varchar(10));

Use the python program (ipython is also possible) to add one hundred thousand pieces of data to the table through the pymsql module

from pymysql import connect

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
    # 获得Cursor对象
    cursor = conn.cursor()
    # 插入10万次数据
    for i in range(100000):
        cursor.execute("insert into test_index values('ha-%d')" % i)
    # 提交数据
    conn.commit()

if __name__ == "__main__":
    main()

Inquire

  • Turn on running time monitoring:
set profiling=1;
  • Find the 10,000th data ha-99999
select * from test_index where title='ha-99999';
  • View the execution time:
show profiles;
  • Create an index for the title column of the table title_index:
create index title_index on test_index(title(10));
  • Execute the query statement:
select * from test_index where title='ha-99999';
  • Check the execution time again
show profiles;

note:

要注意的是,建立太多的索引将会影响更新和插入的速度,因为它需要同样更新每个索引文件。对于一个
经常需要更新和插入的表格,就没有必要为一个很少使用的where字句单独建立索引了,对于比较小的表,
排序的开销不会很大,也没有必要建立另外的索引。

建立索引会占用磁盘空间

Guess you like

Origin blog.csdn.net/weixin_42250835/article/details/90694483