MySQL-DAY03

MySQL-DAY03

1. Constraints

When you create a table, you can add the appropriate constraint to the field in the table, add constraints purpose is to ensure that the data in the table legality, validity and completeness.

Common constraints:

  • Non-empty constraint (not null): Constraint field can not be NULL

  • The only constraint (unique): Constraint field can not be repeated

  • Primary key constraint (primary key): Constraint neither field is NULL, can not be repeated (referred PK)

    • Each table should have a primary key, the master key may be identified record uniqueness of primary keys into a single master key and composite (combined) primary key, a single master key is a field configuration, the composite (combined) primary key is made comprising plural fields.

  • Foreign key constraints (foreign key): ... (referred to as FK)

  • Check constraints (check): Note Oracle database has check constraints, but there is no mysql, mysql does not currently support the constraint.

1.1 The primary key constraint

  • Primary key related terms?

    • Primary key constraint: primary key

    • Primary key fields: id field is added after the primary key, id called the primary key field

    • Primary key: id field values ​​are each of a primary key.

  • What is the role of the primary key?

    • Three design paradigms table is required, first paradigm requires any table should have a primary key.

    • Primary key role: It is the primary key value that uniquely identifies the rows in this table among. (Just like a person's identity card number.)

  • Classification of the primary key?

    • The number of fields in the primary key field divided:

      • A single primary key (recommended, commonly used.)

      • Composite primary key (adding together a plurality of fields primary key constraint) (composite primary key is not recommended, since the composite primary key violation three paradigm.)

  • The divided nature of the primary key:

    • Natural primary key: primary key value and business is not the best idea is a natural number of any relationship. (This approach is recommended)

    • Natural key: primary key value and business systems linked, for example: holding a card bank card as a primary key, holding identity card number as the primary key. (Not recommended)

      • Best not to hold the hook and business fields as the primary key. Because later time business once the change occurs, with the primary key value may also need to change, but sometimes there is no way to change, because change could lead to duplicate primary key value.

  • A table's primary key constraint can only have one. (It must be remembered)

    create table t_user(
id int primary key, // 列级约束
username varchar(255),
email varchar(255)
);
create table t_user(
id int,
username varchar(255),
primary key(id) //表级约束
);
  • mysql provide primary key value increment :( very important.)

    drop table if exists t_user; create table t_user( id int primary key auto_increment, // id字段自动维护一个自增的数字,从1开始,以1递增。 username varchar(255) ); insert into t_user(username) values('a'); insert into t_user(username) values('b'); insert into t_user(username) values('c'); insert into t_user(username) values('d'); insert into t_user(username) values('e'); insert into t_user(username) values('f'); select * from t_user;

1.2 foreign key constraints

  • About foreign key constraints related terms:

    • Foreign key constraint: foreign key

    • Foreign key field: Field add foreign key constraint

    • Foreign key value: a value for each foreign key field.

  • The above table built table written statement:

    classno field t_student references cno field t_class table, when the table is called the child table t_student. t_class table is called the parent table.

    • Order requirements:

      • When deleting data, delete the child table, and then delete the parent table.

      • When data is added, first add the parent table, add the child table.

      • When you create a table, first create the parent table, and then create sub-tables.

      • Delete the table, the child table to delete, delete the parent table.

  • Foreign key value can be NULL.

  • Foreign key field references a field of another table when the field is not necessarily referenced primary key, but at least having unique constraints.

2. Storage Engine (understand)

  • Database tables are (when you create a table) specified storage engine to handle.

  • Available server engine depends on the following factors:

    • MySQL version

    • How the server is configured during development

    • Startup Options

  • To understand what storage server has current engines are available, you can use SHOW ENGINES statement:

    mysql> SHOW ENGINES\G
  • When you create a table, use the ENGINE option for the CREATE TABLE statement to explicitly specify the storage engine.

    CREATE TABLE TABLENAME (NO INT) ENGINE = MyISAM;
  • If you do not explicitly specify the storage engine when creating a table, the table uses the current default storage engine

  • The default storage engine can be specified using the default-storage-engine option in the my.ini configuration file.

  • Existing table storage engine can use the ALTER TABLE statement to change:

    ALTER TABLE TABLENAME ENGINE = INNODB;
  • A table storage engine is determined to be used, may be used SHOW CREATE TABLE statement or SHOW TABLE STATUS:

    mysql> SHOW CREATE TABLE emp\G

mysql> SHOW TABLE STATUS LIKE 'emp' \G

3. Transaction

3.1 Overview

A transaction is a complete business logic unit can not be divided.

Transactions can ensure multiple operations atomic, either all succeed, or all three fail.

For a database transaction to ensure that the bulk of the DML (insert delete update) either all succeed, or all three fail.

3.2 Characteristics of things

Transaction has four characteristics: ACID

  • a) Atomicity (Atomicity)

    All the operation of the entire transaction to be completed as a unit (or full cancellation).

    A transaction is the smallest unit of work, it can not be divided.

  • b) Consistency (Consistency)

    Prior to the start and after the end of the transaction, the database remains in a consistent state.

    Services must ensure that multiple DML statements while at the same time the success or failure.

  • c) isolation (Isolation)

    A transaction will not affect the operation of other transactions.

  • d) Persistent (Durability Rev)

    After the transaction is completed, the transaction changes made to the database will be permanently stored in the database, and will not be rolled back.

    The final data must be persisted to hard disk file, the transaction is considered successful conclusion.

3.3 affairs, there are some concepts:

a) transaction (Transaction): number of operations (a group DML)

b) open transactions (Start Transaction)

c) roll back the transaction (rollback)

d) commit the transaction (commit)

e) SET AUTOCOMMIT: disable or enable automatic transaction commit mode

When performing DML statement is in fact open a transaction.

Rollback on the transaction Note: You can only roll back insert, delete and update statements can not be rolled back select (rollback select no meaning), to create, drop, alter these can not be rolled back.

Services only have the effect of DML.

Note: After the rollback, or commit the transaction is over.

3.4 transaction isolation

3.4.1 Isolation Level

Transaction isolation level isolation exists, in theory, four isolation levels include:

  • The first level: Uncommitted Read (read uncommitted)

    • Other matters not yet submitted, we can read the current transaction data to each other uncommitted.

    • Uncommitted Read existence dirty read (Dirty Read) phenomenon: that read data dirty.

  • Level 2: Read Committed (read committed)

    • After the data we can read each other transaction commits.

    • This isolation level to solve: the phenomenon is not a dirty read.

    • Read Committed problems are: non-repeatable read .

  • The third level: Repeatable Read (repeatable read)

    • This isolation level to solve: non-repeatable read problem.

    • The problem with this isolation level the question is: read data is illusion .

    • The isolation level of InnoDB is the default setting.

  • Fourth level: a sequence of the read / serializer read (Serializable)

    • Solve all the problems.

    • Inefficient, require transaction queue.

oracle database default isolation levels are: read committed.

mysql database default isolation levels are: Repeatable Read.

image-20200321201352908

3.4.2 scope

Transaction isolation level scope is divided into two types:

  • Global level: valid for all sessions

  • Session level: only valid for the current session

For example, the isolation level is set to session READ COMMITTED:

mysql> SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
mysql> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

Set the global level isolation level to READ COMMITTED:

Demo level 1: Read Uncommitted 
set global transaction isolation level read uncommitted;
Demo level 2: Read Committed
set global transaction isolation level read committed;
Demo Level 3: repeatable read
set global transaction isolation level repeatable read;

3.4.3 View isolation level

  • Server variables tx_isolation (including session-level and global level two variables) stored in the current session isolation level.

  • To view the current isolation level, accessible tx_isolation variables:

View the current session-level isolation level:

mysql> SELECT @@tx_isolation;
或:
mysql> SELECT @@session.tx_isolation;

View the current global level isolation level:

mysql> SELECT @@global.tx_isolation;

3.5 auto-commit mode

  • Auto-commit mode is used to determine how and when to start new transactions.

  • Enable automatic commit mode:

    • If the auto commit mode is enabled, a single DML statement will default to start a new business.

    • If the statement is successful, the transaction will automatically be submitted, and save the results of the statement permanently.

    • If the statement fails, the transaction is automatically rolled back and canceled the results of the statement.

    • In automatic mode submission, START TRANSACTION statement can still be used to explicitly start the transaction. At this time, a transaction may still contain multiple statements, these statements are unified until the committed or rolled back.

  • Disabling auto-commit mode:

    • If you disable auto-commit, the transaction can span multiple statements.

    • In this case, the transaction may be COMMIT and ROLLBACK statements to explicitly commit or rollback.

  • Auto-commit mode can be controlled by a server variable AUTOCOMMIT.

MySQL> = the AUTOCOMMIT the SET OFF; MySQL> = the ON the AUTOCOMMIT the SET; or MySQL> = the SET OFF the AUTOCOMMIT the SESSION; MySQL> = the ON the AUTOCOMMIT the SESSION the SET; Show Variables like '%% Auto'; - see the status of variables









4 Index

4.1 Principle

Index is used to quickly find a column in a row a specific value.

There is no index, MySQL have to first start with the first record and then read the entire table until it find the relevant line. The larger the table, the more time it takes.

For an ordered field, you can use binary search (Binary Search), which is why the performance can be improved on nature. MYISAM INNODB and are used as a B + Tree index structure.

By B + Tree reduce the scan range, the underlying index is sorted, the partition, the index will carry data in the table, "physical address", then the final data is retrieved through the index, acquires the physical address associated physical address locator table data, efficiency is the highest.

select ename from emp where ename = ' SMITH'; 
is converted to an index by:
SELECT ename from EMP WHERE physical address = 0x3;
  • Primary key, unique default will add an index.

  • According to the primary key of higher query efficiency. Try to retrieve the primary key.

4.2 Classification Index

  • A single index: add an index to a single field

  • Composite Index: multiple fields together to add an index

  • Primary key index: automatically add an index on the primary key

  • Will automatically add an index on the field has the unique constraints: unique index

4.3 Creating an index

When do I need to add an index field:

  • Table amount of data in the field of large

  • Often retrieved, often appear in the where clause field

  • Often field DML operations do not recommend adding an index

Index directory is equivalent to a book.

Primary key indexes are automatically added, so try a higher query efficiency based on the primary key.

create unique index on table index name (column names); 
ALTER Table add unique index table index name (column names);

4.4 to view, use, delete the index

show index from table name; 
EXPLAIN the SELECT column names from table where conditions;
drop index index name on table name;

5 views

5.1 Overview

  • It is a view based on the query (that is, SELECT expression) database object definitions for acquiring local data you want to see and use.

  • The view is sometimes referred to as "virtual table."

  • It can be used from the view of a conventional table (called a "base table"), or other views query data.

  • Obtain data directly from the table relative to the base, the view has the following advantages:

    • Easy access to data

    • It can be used to display different content to different users table

    • To assist table structure adapted to accommodate conventional distal end applications

View Role:

  • Improve retrieval efficiency

  • Hide implementation details to retrieve the table [for] View

image-20200321203237493

5.2 to create, modify, delete, view?

create view myview as select empno,ename from emp;
alter view v_dept_emp as select ename,e.deptno from emp e,dept d where e.deptno = 20;
drop view myview;

Note: The only way DQL statement can view objects created.

A view is CRUD, it will affect the original data table. (Effect of the original table data through a view, the original table is not directly operated)

CRUD operations may be performed on a view.

6 DBA command

6.1 The export data out of the database

Executed in the windows dos command window :( export the entire library)

mysqldump bjpowernode>D:\bjpowernode.sql -uroot -p333

Executed in the windows dos command window :( export specified table among the specified database)

mysqldump bjpowernode emp>D:\bjpowernode.sql -uroot –p123

6.2 Importing Data

create database bjpowernode;
use bjpowernode;
source D:\bjpowernode.sql

7 Database Design three paradigms

Design paradigm is based on the design table. According to this three-table design paradigm of data redundancy does not appear.

Three paradigms:

  • The first paradigm: Any table should have a primary key, and each field of the atom can not be divided.

  • The second paradigm: the first based on the paradigm, all non-primary key fields entirely dependent on the primary key, can not produce partially dependent.

    • Many to many? Three tables, two tables foreign key relationships.

  • Third paradigm: based on the second paradigm, all non-primary key field is directly dependent on the primary key, transfer can not produce dependence.

    • Many? Two tables, plus multi-table foreign key.

One design, there are two options: the primary key sharing, foreign key unique.



Guess you like

Origin www.cnblogs.com/winterriver/p/12542034.html