I moved from my own csdn blog, and found that many blog posts have become vip posts after posting on csdn. I can go to your bar csdn. I can't read my own blog. I have to log in to see it. It's really disgusting

Just at the weekend, we talked about finance and big data in class, and asked to write SQL, and take out the notes we have written before

Review notes of the national MySql Level II exam (experience update after the exam on March 30)


2019 Summer Update: This exam passed with eyes closed. Except for the multiple choice questions, I feel it's not too difficult to recite them


In the afternoon exam on March 30, 2019, the questions were very close to the question bank, and the original questions were also encountered. In addition to the multiple choice questions, I felt good about the exam. After all, I could get a lot of points by copying and pasting

Introduction to examination environment

The environment is win7+Wamp server Rather than imagined linux+mysql MySQL can be opened directly from the exam software. In addition, you can access http://localhost:8888/phpmyadmin Graphical processing (see the address of the third php question for the specific port), which is very interesting. If you can't use the GUI for data, you can also check whether your own questions are correct, whether you have added data to create indexes, views, etc., so the operation question is quite simple (simpler than access)

Operation problem solving skills

  1. Remember to use draft paper to copy the multiple choice questions Sql statement Avoid forgetting grammar in operation questions,
  2. If you really forget, remember to use mysql help The specific rules of the command are as follows:

    If I want to search Create Index Syntax, enter it in MySQL help + Search content

     mysql> help CREATE index;

    Then the syntax and detailed explanation will appear, which is very convenient. Other searches are similar. If the statement is incorrect, the following prompts will be given

  3. Alternatively, you can manually generate sql statements in phpmyadmin, and then copy, edit, and paste them to get the answer.
  4. In addition, once an error statement cannot be executed, it will report an error. If it is executed in branches, it will be convenient for us to locate and check the error,
  5. You may encounter the problem of saving sql to txt. Remember to open Notepad first, do it again, and then save it. You must select the utf-8 encoding format. Ansi is afraid that it will lose points if it does not support Chinese (if you create Notepad first, you cannot select the encoding format!)

Here are some of my suggestions. I wish you all good results


Because the local question bank mysql can't run at all, you can only manually type the notepad to compare the answers I have done several sets of questions and found some rules. The question bank always examines several kinds of things So take notes and review SQL


@[toc]

Key review objects

  • view
  • event
  • trigger
  • Storage process
  • Storage function
  • User creation and permission
  • Backup and restore with MySql
  • PHP and MySql Process oriented interactive

Symbolic meaning [] Indicates optional | It means one more choice


view

A view is a table that is temporarily made according to your own requirements for direct reference next time

Create View

 CREATE [OR REPLACE] VIEW view_name[(column_list)] AS SELECT_statement [WITH [CASCADED | LOCAL] CHECK OPTION]

explain: or replace Indicates that the view with the same name can be replaced optionally column_list Indicates the name of the corresponding column in the replacement view with check option Used for changes on updatable views, cascaded by default It indicates that the change will still meet the requirements of select_statement Conditions of, local Only the definition view is checked

select_statement There are also some limitations:

  1. Cannot contain subquery containing from
  2. In addition to the create view permission, the user also needs to have the relevant permissions inside select_statement
  3. Cannot reference system variable or user variable
  4. Preprocessing statement parameters cannot be referenced
  5. The referenced table or view must exist
  6. If the select statement does not refer to the basic table or source view of the current database, you need to add a database prefix
  7. The ORDER BY clause is allowed in view definitions constructed by SELECT statements. However, if you view the BY statement from a specific view, the ORDER BY clause in the view definition will be ignored
  8. For other options or clauses in the SELECT statement, if the created view also contains these options, the statement execution effect is undefined. For example, if the view definition includes a LIMIT clause and the SELECT statement also uses its own LIMIT clause, MySQL does not define which LIMIT statement to use.

Modify View

 ALTER VIEW view_name[(column_list)] AS SELECT_statement [WITH [CASCADED | LOCAL] CHECK OPTION]

Just write it again

Delete View

 DROP VIEW [IF EXISTS] view_name[,view_name]

event

It can be understood as MySQL Scheduling Task , execute a SQL statement according to the cycle, which can execute a task every second event scheduler It must be turned on. It is turned off by default input SET GLOBAL event_scheduler = ON; Execute

This blog is well written

Create Event

 CREATE  [DEFINER = { user | CURRENT_USER }]  EVENT  [IF NOT EXISTS]  event_name  ON SCHEDULE schedule  [ON COMPLETION [NOT] PRESERVE]  [ENABLE | DISABLE | DISABLE ON SLAVE]  [COMMENT 'comment']  DO event_body;  schedule:  AT timestamp [+ INTERVAL interval] ...  | EVERY interval  [STARTS timestamp [+ INTERVAL interval] ...]  [ENDS timestamp [+ INTERVAL interval] ...]  interval:  quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |  WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |  DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

Definition: event_name : The name of the created event (unique). ON SCHEDULE : Scheduled task. schedule : Determine the execution time and frequency of the event (note that the time must be in the future, and the past time will make errors). There are two forms: AT and EVERY. [ON COMPLETION [NOT] PRESERVE] : optional. The default is ON COMPLETION NOT PRESERVE, which means that the event is automatically dropped after the scheduled task is executed; ON COMPLETION PRESERVE will not be dropped. [COMMENT 'comment'] : optional; comment is used to describe event; It is equivalent to comment. The maximum length is 64 bytes. [ENABLE | DISABLE] : Set the status of the event. The default ENABLE: indicates that the system attempts to execute the event. DISABLE: closes the event, which can be modified with alter DO event_body : The sql statement to be executed (can be a compound statement). CREATE EVENT is legal when used in stored procedures.

Modify Event

 ALTER  [DEFINER = { user | CURRENT_USER }]  EVENT event_name  [ON SCHEDULE schedule]  [ON COMPLETION [NOT] PRESERVE]  [RENAME TO new_event_name]  [ENABLE | DISABLE | DISABLE ON SLAVE]  [COMMENT 'comment']  [DO event_body]

Delete Event

 DROP EVENT [IF EXISTS] event_name

trigger

As the name implies, once any condition is met, only the statement will be executed It is a bit similar to the cascade restrict in the foreign key on delete

Four Elements of Trigger

Monitoring place (table), monitoring event (insert/update/delete), triggering time (after/before), triggering event (insert/update/delete)

Create Trigger

 CREATE TRIGGER Trigger Name After | before (trigger time) Insert | update | delete (trigger event) On table name (monitoring address) FOR EACH ROW -- This sentence is dead in MySQL. There are only row triggers and table triggers in Oracle BEGIN sql1 ... sqlN END;

Statement explanation: Trigger Time Before | After: indicates whether the trigger starts before or after the activation statement.

  • Before Complete triggering first , and then add, delete and modify data If you want to verify whether the new data meets the use limit, use before
  • After Yes Complete data addition, deletion and modification first , re trigger If you want to complete several or more changes after the trigger statement executes, you usually use the after option. Trigger event:
    1. INSERT inserts a new row to activate the trigger.
    2. The trigger is activated when UPDATE changes a row in the table.
    3. The trigger is activated when DELETE deletes a row from the table.

How to reference row values when using triggers

  • about insert For the new row new To represent; The value of each column in the row, using New. Column name To represent.
  • about delete For the deleted lines, use old To represent the value of each column in the row, use Old. Column name To represent.
  • about update For the modified row, the data before modification is used old To indicate that, Old. Column name Reference the value in the row before modification; The modified data is used new To indicate that, New. Column name Reference the value in the modified row.

Delete trigger

 DROP TRIGGER [IF EXISTS] [database name.] trigger name

Note that drop trigger requires super permission


Storage process

A stored procedure is a set of SQL statements in MySQL to complete a specific function. In essence, it is a piece of code stored in the database

Semicolon; Escape

It is often used in the process of establishing storage DELIMITER To proceed ; To avoid early termination before executing multiple statements

 DELIMITER $$

· $$ It is a user-defined ending symbol, which can be defined by yourself, but backslash should be avoided \ Because it is an escape character of MySQL

Create Stored Procedure

 DELIMITER $$ CREATE  PROCEDURE sp_name([[IN|OUT|INOUT] param_name type][,...]])   //This is similar to function sp_name (a as int, b as int) BEGIN SQL1; SQL2; ... SQLN; END $$

Statement explanation: · Input parameter IN Enables data to be passed to a stored procedure Output parameter OUT Used when the stored procedure needs to return an operation result Input/output parameter INOUT Set of the first two

DECLARE Declare Local Variables
 DECLARE var_name[,...]type[DEFAULT value]

for example DECLARE sno CHAR(10) DEFAULT '3'; Precautions ·Can only be declared in the begin end header ·Scope: begin end ·To distinguish from MySQL, you can use @Variable name As variable

SET statement

Use set to assign values to local variables

 SET var_name=expr[,var_name=expr]

for example set sno='10000'

Process judgment statement
  1. Conditional judgement

    • if-else
     IF condition THEN statement [ELSEIF condition THEN statement] [ELSE statement] END IF
    • case
     CASE case_value WHEN when_value THEN statement WHEN when_value THEN statement END CASE

    This method is to use case_value and when_value for comparison. If it is true, execute The second method

     CASE  WHEN condition THEN statement WHEN condition THEN statement ELSE statement END CASE

    This method is more convenient

  2. Loop statement

    • WHILE cycle
     WHILE search_condition DO statement END WHILE
    • REPEAT cycle
     REPEAT statement UNTIL search_condition END REPEAT
    • LOOP cycle
     LOOP statement END LOOP

    I don't know how to use this

cursor

A cursor is a result set retrieved by a SELECT statement. After the cursor is stored, you can browse its data

  1. declare cursor

     DECLARE cursor_name CURSOR FOR select_statement
  2. Open Cursor

     DECLARE cursor_name CURSOR FOR select_statement
  3. Read data

     FETCH cursor_name INTO var_name[,...]
  4. Close Cursor

     CLOSE cursor_name

Call stored procedure

Directly like Visual Basic call Just do it

 CALL sp_name([parameter[,...]])

Delete Stored Procedure

 DROP PROCEDURE FUNCTION[IF EXISTS]sp_name

Storage function

difference Storage process Storage function
Output parameters need No, I have a return
call To use CALL Direct reference

Create storage function

 DELIMITER $$; CREATE  FUNCTION sp_name([param_name type[,...]]) RETURNS type BEGIN sql1; sql2; ... sqln; END $$

Call storage function

 SELECT sp_name(param)

Delete Stored Function

 DROP FUNCTION sp_name;

User creation and permission

Create User

 CREATE USER 'name'@'localhost' [IDENTIFIED BY 'password']

Permission settings

Grant permission GRANT
 GRANT permission name ON table name TO  name@localhost [WITH with_statement]

Note: with Later common WITH GRANT OPTION

Revoke permission REVOKE
 REVOKE permission name ON table name FROM  name@localhost

MySql data backup and recovery

This is very important! In the past, because I didn't know that I could backup directly from MySQL, I always had to phpmyadmin To export and import, if you use the built-in mysqldump Functions will be much faster

MySQL dump backup data

  1. Data Table Export
 Mysqldump - u username - p Password Database Data Table>Export File Address File Name.sql
  1. Backup database system
 Mysqldump - u username - p password -- all databases>export filename.sql
  1. Back up table structure and data separately
 mysqldump -u root -p**** --tab=filename.sql Table data and structure can be backed up separately

Note: There is no space between - p and password!!!!!!!

MySQL recovery data

Pay attention to data recovery Not ` ` mysqldump Has

  1. Restore the structure and data of the database
 mysql -u root -p **** db_database< database.sql
  1. Recover data only
 mysqlimport -u root -p **** database.sql

PHP and MySql Process oriented interactive

Find two very good articles! MySQL is based on process oriented programming MySQL is based on object-oriented programming

Because the questions in the mysql level 2 exam are almost process oriented, you must use process oriented programming, or you won't get points In addition, because the sentence of grade examination is very early, and obviously what can be completed in one step must be divided into two steps, we must pay attention to memorizing the sentence

Connect Database

 <? php header("Content-type:text/html;charset=utf-8"); $link  =  mysqli_connect( 'localhost' ,  'root' ,  '' ,  'test' ) or die ('Connect Error:'.mysqli_connect_error()); //This is a general procedure oriented php using mysqli connection method $con=mysql_connect("localhost:3306","root","") Or die ("Database server connection failed!<br>"); Mysql_select_db ('test ', $con) or die ("Database selection failed!<br>"); //This is a foolishly connected method, which examines the statements used to select the database ?>

Set Character Set

 mysqli_set_charset($link,'UTF8'); //Mysqli process oriented mysql_query("set column 'uft8"); //Set properties for a column

Execute sql statement (insert, read, update, delete)

insert data
 $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', ' john@example.com ')"; if (mysqli_query($conn, $sql)) { Echo "New record inserted successfully"; } else { echo "Error: " . $ sql .  "<br>" .  mysqli_error($conn); }
Read data
 $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { //Output Data while($row = mysqli_fetch_assoc($result)) { echo "id: " . $ row["id"].  " - Name: " . $ row["firstname"].  " " . $ row["lastname"].  "<br>"; } } else { Echo "0 result"; }

Explanation: mysql_fetch_array(data[,array_type]) Array_type type

  1. MYSQL_NUM numeric array
  2. MYSQL_ASSOC associative array (key value pair)
  3. The default value of MYSQL_BOTH, which generates both numbers and associative arrays mysql_fetch_row(data) Generate numeric array mysql_fetch_assoc(data) Generate associative array (key value pair)

It's almost like this. The other is to grind and brush the multiple choice questions slowly