Study Notes day39

view

What is a view?

  A query result is a virtual table, it will be preserved this virtual table, it becomes a view.

Why view?

  When the frequent need to use multiple tables even watch the results, you can generate a good view in advance, directly after the call to avoid repeated write operations even table sql statement.

How to use the view?

 create view teacher_course as select * from teacher INNER JOIN course
 on teacher.tid = course.teacher_id;

1, only a table structure view, data view or from the original table

2, do not change the data in the view table

3, frequent use will not generally view to write business logic

# Need to emphasize the point 
. "" " 
1 In the hard disk, the file structure table view only, no table data file
 2 The view is typically used to query, try not to modify the data view 
." "" 



# Point to ponder: Development process will not go using views? 
"" " 
No, the view is a MySQL function, if your project a lot of use to the view, that means when you want to expand the latter a function of this function happens to need to make changes to the view, which means you need in the first mysql here to view changed a bit, and then go to modify the application corresponding sql statement, which relates to the issue of inter-departmental communication, so do not usually use a view, but to extend the functionality through re-edit sql statement 

"" "

trigger

What is the trigger?

  In the case of satisfying a particular table data add, delete, change, automatically trigger the trigger function is called

Why the flip-flop?

  Trigger specifically for our growth to insert a table of some, delete delete, change update behavior, this kind of behavior once executed it will trigger execution of a trigger that automatically runs another piece of sql code.

How to use a trigger?

  Triggers are divided into six cases: the former increases, the increase, the former delete, delete after, before change, after change.

Fixed grammar

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

比如:
create trigger tri_(before/after)_(insert/update/delete)_t1 (after/before)
insert/update/delete on t1 for each row
begin
      sql语句
end

MySQL end of modifier

#Mysql the terminator (;) can be modified 
delimiter $$ valid only for the current window 
# back after use is preferably modified
DELIMITER;

Case

# Write a trigger, trigger after inserting data to the CMD table, and then judges whether the inserted success is yes or no, if it is no, go out into the errlog in a data plug
 the CREATE  TABLE cmd ( 
    the above mentioned id INT  PRIMARY  KEY AUTO_INCREMENT,
     the USER  CHAR ( 32 ), 
    PRIV CHAR ( 10 ), 
    cmd CHAR ( 64 ), 
    SUB_TIME datetime , # submission time 
    Success enum ( ' Yes ' , ' NO ' ) representative of # 0 fails 
); 

the CREATE  TABLE errlog ( 
    ID the INT  a PRIMARY KEY AUTO_INCREMENT, 
    err_cmd CHAR ( 64 ), 
    err_time datetime 

# write trigger 
# added: NEW to refer to the object is the current record 
DELIMITER $$ 
Create  Trigger tri_after_insert_cmd After INSERT  ON cmd for each Row
 the begin 
    IF NEW.success =  ' NO '  the then 
        INSERT  INTO errlog (err_cmd, err_time) values (NEW.cmd, NEW.sub_time);
     End  IF ;
 End $$ 
DELIMITER;
# Delete trigger
 drop  the Trigger tri_before_insert_user;

thing

Transaction contains a lot of sql statement, sql these at the same time either succeed, or even think about a success

Four characteristics of the transaction: ACID

A: atomicity (atomicity), a transaction is an indivisible unit of work, including many affairs operations, either do or do not do.

B: consistency (consistency), that the database transaction must be changed from one consistent state to another consistent state. Consistency and atomicity are closely related.

I: performing isolation (isolation), a transaction can not be interfere with other transactions. I.e., operation and use of the data inside a concurrent transaction other things are isolated and can not interfere with each other between the respective transaction executed concurrently.

D: persistence (durability), also known as persistent permanent (permanence), means that once a transaction is committed, it changed the database should be permanent, then the other operation or malfunction should not have any of its influences.

Use affairs

# How to open a transaction 
    Start Transaction 
# transaction rollback 
    ROLLBACK 
# permanent changes 
    commit 

state ## once again use the commit rollback does not return before the

Stored Procedures

Custom function is similar to the python, the sql statement inside the package database operations, subsequent want to achieve the appropriate action can only call the stored procedure.

# Syntax result 
      DELIMITER $$ 
      Create  Procedure P1 ()
       the begin 
          SELECT  *  from  User ;
       End $$ 
      DELIMITER; 

# arguments 
      DELIMITER $$ 
      Create  Procedure P1 (
           in m int , # can not be returned out
           in n- int , 
          OUT RES int , # can be returned 
          INOUT xxx int , # and can enter either a 
      ) 
      the begin 
          the SELECT  *  from  the User ;
       End $$
      DELIMITER; 

# call
call p1 ()
Examples # 
DELIMITER $$ 
Create  Procedure P1 (
     in m int , # represents in this parameter must be passed not only be returned out
     in n- int , 
    OUT RES int   # OUT indicates that this parameter can be returned out, there is represented a inout which can be returned may be passed out 
) 
the begin 
    SELECT tname from Teacher WHERE TID > m and TID < n-;
     SET RES = 0 ; # is similar to a flag for identifying whether the memory is executed successfully
 End $$ 
DELIMITER; 

Call P1 () # call a stored procedure parameter passing and 
## mass participation, the flag will be passed directly into the error 
set @res  =  10    # sets a variable binding relationship between the value 

after passing through the 
SELECT  @res 
returns the execution result stored procedure after completion See

Note: The stored procedure can only be used in the library at the following libraries defined below.

Call a stored procedure by pymysql

import pymysql

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day38',
    charset = 'utf8',
    autocommit = True
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# Call p1 () mysql call 
# callproc () pymysql called 
Cursor .callproc ( ' P1 ' , ( . 1 , . 5 , 10 )) 
# internal automatic variable name stored value corresponding 
Print ( Cursor .fetchall ()) 
"" " 
@ _p1_0 = . 1 
@ _p1_1 = . 5 
@ _p1_2 = 10 

@_ index value stored procedure names _ 
" "" 
Cursor . Execute ( ' SELECT @ _p1_0 ' )
 Print ( Cursor .fetchall ())
 Cursor . Execute ( 'select @_p1_1')
print(cursor.fetchall())
cursor.execute('select @_p1_2')
print(cursor.fetchall())

function

Custom Functions

#! ! ! note! ! ! 
# Do not write function sql statement (otherwise it will error), the function is just a function is being applied in a sql functions 
# If the order ... in the begin End write sql ... Please use stored procedures 

" "" 
DELIMITER // 
Create  function F1 ( 
    I1 int , 
    I2 int )
 Returns  int 
the BEGIN 
    DECLARE NUM int ;
     SET NUM = I1 + I2;
     return (NUM);
 the END  // 
DELIMITER; 
"" " 
DELIMITER // 
Create  function F5 ( 
    I int 
)
returns int
begin
    declare res int default 0;
    if i = 10 then
        set res=100;
    elseif i = 20 then
        set res=200;
    elseif i = 30 then
        set res=300;
    else
        set res=400;
    end if;
    return res;
end //
delimiter ;
"""

Process Control

Conditional statements if

delimiter //
CREATE PROCEDURE proc_if ()
BEGIN
    
    declare i int default 0;
    if i = 1 THEN
        SELECT 1;
    ELSEIF i = 2 THEN
        SELECT 2;
    ELSE
        SELECT 7;
    END IF;

END //
delimiter ;

While loop

delimiter //
CREATE PROCEDURE proc_while ()
BEGIN

    DECLARE num INT ;
    SET num = 0 ;
    WHILE num < 10 DO
        SELECT
            num ;
        SET num = num + 1 ;
    END WHILE ;

END //
delimiter ;

index

Knowledge Review: Data are, inevitably need to query data on the hard disk IO operations presence

MySQL indexes also called "key", it is a data structure storage engine used to quickly find the record.

  • primary key
  • unique key
  • index key

Because foregin key is not used to speed up queries, it is not within our terms of three key above, the first two in addition to accelerating the query results as well as additional constraints with (primary key: a non-empty and the only ; unique key: unique), but without any constraint index key function will help you speed up queries.

Index is essentially a data structure that is similar to the output directory, mean that we should first find out the directory at the time of check data to find data, rather than querying data with page-turning way.

Nature: all want to get through shrinking the scope of the data to select the final results handsome desired, while the random time becomes a chronological order, that is, with this indexing mechanism, we can always use Find a way to lock the same data.

The impact of index

  • Subject to the availability of large amounts of data in tables, creating the index can be slow
  • After the index is created, query performance to the table will be greatly improved, but the write performance is reduced 

B + Tree

Only leaf nodes store the actual data, root and branch nodes exist only virtual data, the number of inquiries by the level of the decision tree, the lower the level of the less often.

 We know the size of a disk is certain, that is, the amount of data stored is certain, the more data we have in each data item and storing so the fewer points layer, query speed too fast, then a table, index established what fields can reduce the height of the tree hierarchy >>> primary key id field.

Clustered index (primary key)

Clustered index refers to the primary key of the table, innodb engine specified in the table must have a primary key.

We recall the construction of the table storage engine, myisam there are three files in the built form of time, and innodb table is built in two files, frm file stores the table structure, you can not store the index, with the index that is innodb data release in idb table data file. 

Features : leaf node to put a complete record of a strip

Secondary index (unique, index)

Secondary indexes: query data when not all be used as a screening id conditions, may also use the information field name, password, etc., then you can not use this time to speed up query performance clustered index. It needs to be indexed to other fields, these indexes will post secondary indexes.

Features : leaf node is stored in that record of the primary key values corresponding to the index of the auxiliary

the SELECT name from  the User  the WHERE name = ' Jason ' ; 

# The above statement is called a covering index: only the leaf nodes of the secondary index has found all the data we want 

the SELECT Age from  the User  the WHERE name = ' Jason ' ; 

# above statement called non-covering indexes, though, when the index hit a query field name, but to check that the age field, so # also need to use a primary key was to find

 

Guess you like

Origin www.cnblogs.com/wangnanfei/p/11400859.html