当前位置:网站首页>MySQL notes

MySQL notes

2022-06-22 13:01:00 Maple forest

MYSQL brief introduction

MySQL It's an open source Relational database Management system .

MYSQL Directory structure of

1、bin Catalog : Used to store some Executable file , Such as mysql.exe etc. .

2、include Catalog : Used to store some of the included The header file , Such as mysql.h etc. .

3、lib Catalog : Used to store some The library files .

4、share Catalog : Used to store error message Character set file etc. .

5、data Catalog : Used to place some Log files as well as database .

6、my.ini file : Profile of the database .

Command line start mysql

net start mysql80→ Start the service

net stop mysql80→ Out of Service

MySql The login :

Parameters

describe

-u

user name

-p

password

-V

Output version information and exit

-h

The host address

MySql The exit of :       exit

                                quit

                                \q

MySql Common commands

1、mysqladmin The command is used to change the user password

Command format :mysqladmin -u user name -p Old password password New password

2、show databases The command is used to display all databases

Command format :show databases;

3、use The command uses the database

Command format :use < Database name >;

4、select The command displays the current connection ( choice ) Information about

Display the currently connected database :select database();

Display the current server version :select version();

Display the current date time :select now();

Show current user :select user();

Create database : Divide an area on the system disk for data storage and management .

create database [if not exists] db_name;    // Create database

[default] character set[=] charset_name;    // Specify the default character set

modify the database

alter database db_name;   // modify the database

[default] character set[=] charset_name;   // Specify the default character set

Delete database

drop database [if not exists] db_name;  // Delete database

MYSQL Data structure of

data type : Refers to the data column 、 Stored procedure parameters 、 Data characteristics of expressions and local variables , It determines the storage format of the data , Represents different types of information .

integer :                 tinyint                 1 byte

                            smallint               2 byte

                            mediumint           3 byte

                            int                        4 byte

                            bigint                   8 byte

Floating point type :   float[(m,d)]                        4 byte

                         double[(m,d)]                   8 byte

Fixed point number type :   decimal[(m,d)]

m Is the accuracy (= Number of integers + Decimal digit ),d Is the scale ( The number of digits after the decimal point )

Floating point types store in the database Approximate value , The fixed-point type is stored in the database The exact value

Date time type :   type                                   Number of bytes                Representation form

                         year                                   1                       yyyy

                         time                                   3                       hh:mm:ss

                         date                                   4                       yyyy-mm-dd

                         datetime                            8                       yyyy-mm-dd hh:mm:ss

                         timestamp                         4                       yyyy-mm-dd hh:mm:ss

Character :           type                                   Storage requirements

                         char(m)                             Fixed length type ,m Bytes

                         varchar(m)                        Variable length ,l+1 Bytes

                         tinytext                              0~255

                         text                                    0~65535

                         mediumtext                       0~2 Of 24 Power -1

                         longtext                             0~2 Of 32 Power -1

                         enum(‘value1’,’value2’,…)   Depends on the number of enumeration values ( most 65,535 It's worth ) Select a value        

                                                                      example : Gender enum(‘ male ’,’ Woman ’)

                         set(‘value1’,’value2’,…)      Depending on set Number of members ( most 64 Members ) Select multiple values

                                                  

Operation of database table structure

Create database tables

create table < Table name >

(

Name 1 data type [ Column level constraints ][ The default value is ],

Name 2 data type [ Column level constraints ][ The default value is ],

……

[ Table level constraints ]

);

Copy database tables

create table surface 1 as select * from surface 2;

View database tables

show tables [from db_name];

Look at the basic structure of the data table

1.show columns from tbl_name;

2.describe < Table name >;/desc < Table name >;

See table detail structure statement , Can be used to display the creation statement of the data table

show create table tbl_name;

① Add columns

alter table < Table name >

add < New column names >< data type >

[ constraint condition ][first|after Column name already exists ];

② Change column names

alter table < Table name >

              change < Old column names >< New column names >< New data types >;

③ Change the data type of the column

alter table < Table name > modify < Name >< data type >;

alter table < Table name > change < Old column names >< New column names >< data type >;

④ Modify the arrangement position of columns

alter table < Table name >

              modify < Column 1> < data type > first|after < Column 2>;

⑤ Delete column

alter table < Table name > drop < Name >;

⑥ Modify the name of the table

alter table < The old name of the table > rename [to] < The new name of the table >;

Delete database tables

Use drop table You can delete one or more data tables that are not associated with other tables at one time .

drop table [if exists] surface 1, surface 2,… surface n;

Table partitioning : It is to divide the data of a table into multiple blocks , These blocks can be on the same disk , It can also be on different disks , But all the data is still in one table .

show plugins;                   // Determine whether the database version supports table partition

The following information is displayed to support

  

Create table partition

Use... When creating tables :partition by type ( Field )

range Partition :

Partition according to the range value of a specified column .

Use values less than Operator definition partition .

example :      create table bookinfo(          // The table definition

                book_id int,

                book_name varchar(20)

             )

             partition by range(book_id)(        // Define partition types and fields

                partition p1 values less than (20109999),        // The definition of the zone

                partition p2 values less than (20159999),

                partition p3 values less than MAXVALUE

             );

MYSQL constraint

Constraint is a kind of restriction , It limits the data of a table's rows or columns , To ensure the integrity of the table 、 Uniqueness .

Constraint type           Non empty constraint            Primary key constraint              Unique constraint            Default constraint             Foreign key constraints

keyword              not null            primary key          unique              default                foreign key

Non empty constraint : The value of the field cannot be empty . For fields that use non null constraints, if the user is adding data , No value specified , The database system will report an error .

Rule of grammar : Name data type not null;

null: Field value can be empty .

not null: Field value cannot be empty .

Primary key constraint : The data of primary key column is required to be unique , And cannot be empty , A primary key can uniquely identify a record in a table .

1、 Single field primary key

① Specify the primary key while defining the column

Name data type primary key;

② Specify the primary key after the column definition

[constraint < Constraint name >] primary key ( Name );

2、 Multi field union primary key ( Or composite primary key )

The primary key has multiple fields ( Column ) To combine .

primary key( Field 1, Field 2,… Field n);

Add primary key constraint when modifying table

① alter table < Table name > modify < Name > < data type > primary key;

② alter table < Table name > add primary key ( Name );

③ alter table < Table name > add constraint < Constraint name > primary key ( Name );

Delete primary key :alter table < Table name > drop primary key;

Unique constraint : This column is required to be unique , Allow null , A unique constraint ensures that there are no duplicate references to columns or columns .

Add unique constraints when modifying tables

① alter table < Table name > modify < Name > < data type > unique;

② alter table < Table name > add unique( Name );

③ alter table < Table name > add constraint < Constraint name > unique( Name );

Delete unique constraint

① alter table < Table name > drop index < Constraint name >;

② alter table < Table name > drop key < Constraint name >;

Default constraint : Specify the default value for a column .

Rule of grammar : Name data type default The default value is ;

Add unique constraints when modifying tables

① alter table < Table name > modify < Name > < data type > default The default value is ;

② alter table < Table name > alter column < Name > set default The default value is ;

Delete default constraint

① alter table < Table name > modify < Name > < data type >;

② alter table < Table name > alter column < Name > drop default;

Foreign key constraints

Foreign keys : Used to establish a link between the data of two tables , It can make one or more columns .

Foreign keys correspond to referential integrity , The foreign key of a table can be null , If not null , Then each foreign key value must be equal to a value of the primary key in another table .

Grammar format :        [constraint < Foreign key constraint name >] foreign key( Name )

                          references < Main table name >( Primary key );

Add foreign key constraints when modifying tables

alter table < Table name > add foreign key( Name ) references < Main table name >( Primary key );

Delete foreign key constraint

alter table < Table name > drop foreign key < Constraint name >;

Reference operation of foreign key constraint

cascade: Delete or update from the parent table and automatically delete or update the matching rows in the child table

Realize cascading deletion

[constraint < Foreign key constraint name >] foreign key( Name )

references < Main table name >( Primary key ) on delete cascade;

Graphical management tools

MySql workbench Is a special for users to create 、 modify 、 Execute and optimize SQL Of Visualization tools , Through it, developers can easily manage database data .

SQLyog It's an easy to use 、 Fast and simple graphical management MYSQL Database tools , It can effectively manage the database in any place .

Operation of database table records

① Insert data for all columns of the table

insert into Table name ( Data columns ) values( data );

② Insert multiple records

insert into Table name ( Data columns ) values( data 1),( data 2),…,( data n);

③ Insert the query results into the table

insert into Table name ( Data columns ) select ( Data columns ) from Table name where Conditions ;

Set the attributes of the table to be automatically added

Grammar format : Name data type auto_increment

notes :auto_increment The field of the constraint can be any integer type .

Available when creating tables ” auto_increment=n” Option to specify a self increasing initial value .

Add self incrementing columns to existing tables

alter table Table name modify Name data type auto_increment;

Modify the starting value of auto increment column

alter table Table name auto_increment = x;( After modification auto_increment The starting value of the column starts from x Start )

Remove the self incrementing column

alter table biaoming modify Name data type ;

Update of single table data records

Grammar format :update Table name set Name 1= Data values 1,…, Name n= Data values n where( Conditions );

Deletion of single table records

① delete from Table name [where < Conditions >];

② truncate table Table name ;

truncate The original table will be dropped directly , And recreate a table .

No duplicate query results

select distinct Name from Table name ;

Use distinct Key indication MySQL Eliminate duplicate record values .

Query null value

select * from Table name where Name is null;

You can query a column of records with empty content .

Group query

[group by Name ][having < Conditional expression >];

group by Usually used with aggregate functions .

having Define the conditions to be met for displaying records , Only groups that meet the conditions will be displayed .

Query results Sort

order by Name [asc|desc];

use limit Limit the number of query results

limit Keyword can return records at a specified location

Grammar format :limit [ Position offset ,] Row number ;

explain : The position offset of the first record is 0, The second is 1,… And so on .

Operators and functions

Arithmetic operators are used for various numerical operations

+            -           *            /            %

Add       Subtraction       Multiplication       division       Remainder ( modulus )

Comparison operator

>、<                                  Greater than 、 Less than

>=、<=                              Greater than or equal to 、 Less than or equal to

=                                         be equal to

<> (!=)                               It's not equal to

is (not) null                        Judge whether a value is empty ( Or not empty )

between…and                    Determine whether a value is between two values

(not) in                                Judge a value as ( Or not )in Values in the list

Like                                    Wildcard match

example :SELECT * FROM readerinfo WHERE NAME IN(' Zhang Fei ',' Li Yue ',' Wang Peng ');

wildcard :            %           → Any number of characters

                           _            → Represents a character

Logical operators

and                                    Logic and

or                                       Logic or

not                                     Logic is not

Numerical function : It is mainly used to process numerical data .

① Get the function of an integer

        ceil(x): Return is greater than the x The minimum integer value of .

        floor(x): Back to less than x The maximum integer value of .

② A rounded function

        round(x): Returns the closest parameter x The integer of , For parameters x To round .

        round(x,y): Returns the closest parameter x Number of numbers , Its value is retained to... After the decimal point y position , if y negative , Will keep x To the left of the decimal point y position .

③ Truncation function

        truncate(x,y): Return after being rounded to the decimal point y Digit number x. if y The value of is 0, The result is an integer , if y The value of is negative , Then cut off x The third from the left of the decimal point y All the lower values after the beginning of the bit .

④ modulus ( Seeking remainder )

        mod(x,y): return x By y The remainder after division

⑤ Random function

        rand(): Randomly generated 0~1 Floating point value between .

Character functions : It is mainly used to process string data in the database .

① String concatenation function

        concat(s1,s2,…): The return result is the string generated by the connection parameter , If any parameter is null, The return value is null.

        concat_ws(x,s1,s2,…): The first parameter x Is a separator for other parameters , The position of the separator is placed between the two strings to be connected , The separator can be a string , It can also be other parameters , If the separator is null, The result is null.

② Letter conversion case function

        lower(str): You can string str All alphabetic characters in are converted to lowercase letters .

        upper(str): You can string str All alphabetic characters in are converted to uppercase letters .

③ Function to find the length of string

        length(str): The return value is the byte length of the string .

④ Function to delete spaces

        ltrim(s): Return string s, The space character to the left of the character is deleted .

        rtrim(s): Return string s, The space character to the right of the character is deleted .

        trim(s): Delete the spaces on both sides of the string .

⑤ Intercepting string

        substring(s,n,len): with len Parameter format , From a string s Return a length the same as len Substring with the same character , Starting from position n.n If it's a negative number , The position of the substring starts at the end of the string n Characters .

⑥ Get string function of specified length

        left(s,n): Return string s The far left of the beginning n Characters .

        right(s,n): Returns the rightmost... In a string n Characters .

⑦ Substitution function

        replace(str,from_str,to_str): In string str All the strings that appear in from_str All to_str Replace , Then return this string .

⑧ Format function

        format(x,n): The digital x format , And keep the decimal point after... In the way of rounding n position , The result is returned as a string . if n by 0, Then the returned result does not contain decimal part .

Date time function : It is mainly used to process date and time values

① Function to get the current date

        curdate() and current_date(): Set the current date according to ’YYYY-MM-DD’ or YYYYMMDD The value of the format returns , The specific format depends on the function in the context of string or number .

② Function to get the current time

        curtime() and current_time(): Change the current time to ’HH:MM:SS’ or HHMMSS The format returns , The specific format depends on the function in the context of string or number .

③ Get the current date and time

        now() and sysdate(): Returns the current date and time value . The format is ’YYYY-MM-DD HH:MM:SS’ or YYYYMMDDHHMMSS. The specific format depends on the function in the context of string or number .

④ Perform the addition of dates

        date_add(date,interval expr type):date It's a datetime or date value , Used to specify the starting time .expr It's an expression , Used to specify the interval value added or subtracted from the start date .type Keyword , It indicates how the expression is interpreted , Such as :year,month,day,week,hour etc. .

⑤ Calculate the number of days between two dates

        datediff(date1,date2): Return to start time date1 And end time date2 Days between .

⑥ Date formatting

        date_format(date,format): according to format Display... In the specified format date value .

Time date format :  %b: Abbreviated name of the month (jan…dec)

                           %c: month , Digital form (0…12)

                           %m: month , Digital form (00…12)

                           %M: The name of the month (january…december)

                           %d: Date of the month , Digital form (00…31)

                           %e: Date of the month , Digital form (0…31)

                           %Y:4 The number of digits represents the year

                           %y:2 The number of digits represents the year

Aggregate functions : Do not return the data in the actual table , Only analyze and summarize the obtained data .

              name                     describe

              avg()                    Returns the average of a column

              count()                Returns the number of rows in a column

              max()                   Returns the maximum value of a column

              min()                    Returns the minimum value of a column

              sum()                   Returns the sum of a column

System information function

1、version(): Returns the current MySQL The version number of the server version .

2、connection_id(): return MySQL The number of times the server is currently connected , Each connection has its own unique ID.

3、database() and schema(): Returns the current database name .

4、user(): Function to get the user name , Returns the name of the currently logged in user .

Encryption function : It is mainly used for data encryption and interface processing , To ensure that some important data are not obtained by others .

1、 Information digest algorithm

md5(str): You can encrypt strings , The encrypted value is expressed in 32 Returns... As a binary string of hexadecimal digits , If the parameter is null, Then return to null.

2、 cryptographic algorithm

password(str): From the original plaintext password str Calculate and return the encrypted password string , When the parameter is null, return null.

Subquery

A subquery is a query that is nested within other SQL Query statement within statement .

Subqueries are nested within queries , And must always appear in parentheses .

The result of the subquery is used as the filter condition of another query .

use anyallsome Keyword modifier subquery

1、 After the comparison operator .

2、any and some Synonyms , Indicates that any condition in the inner sub loop is satisfied .

3、all Indicates that all inner query conditions need to be met at the same time .

in keyword : When performing a subquery , The inner query statement returns only one data column , The values in this data column will be provided to the outer query statement for comparison .

not in And in The opposite is true

example :select * from table where exists( Subquery );

① Determine whether the sub query returns rows ;

② If you return , that exists As the result of the true;

③ If no rows are returned , that exists The result returned is false.

Use subquery when inserting records

insert into select Statement to copy data from a table , Then insert the data into an existing table .

Multi table join query

Grammatical structure :       table_reference

                         [inner] join {left|right} [outer] join

                         Table_reference

                         on conditional_ecpr

Internal connection : Query and select data from multiple tables according to the connection conditions , Show the data rows in these tables that match the connection conditions , Combine into a new record .

Grammatical structure :        select column_list

                          From t1

                          [inner] join t2 on join_condition1

                          [inner join t2 on join_condition2

                          …]

                          where where_conditions;

External connection : Query associated rows in multiple tables .

The left outer join : Display all records in the left table , The right table shows the records that meet the connection conditions .

Right connection : Display all records in the right table , The left table shows the records that meet the connection conditions .

Grammatical structure :        select column_list

                          From t1

                          left|right [outer] join t2 on join_condition1;

Self join : If in a join query , The two tables involved are the same table .

Self join is a special kind of join query , It means that interconnected tables are physically the same table , But it can be logically divided into two tables .

example :     select t1.category_id as ' Book category number ',

             t1.category as ' Book category name ',

             t2.category as ' Book superior classification name '

             from bookcategory t1

             left join bookcategory t2 ON t.parent_id = t2.category_id;

Multi table update

update tabl1 {[inner] join | {left | right} [outer] join} table2

on Connection condition

set Name 1 = { value 1 | default}

[, Name 2 = { value 2 | default}]…

[where filter ]

Multi table record deletion

delete surface 1[.*], surface 2[.*]

from surface 1 { Internal connection | External connection } surface 2

on Connection condition

[where filter ]

MySQL The custom function of

Custom function

function ( Storage function )

        1、 A return value is required ;

        2、 You can specify 0~n Parameters .

Grammar format :        create function Function name ([ Parameters ])

                          returns type

                          [characteristics] The body of the function

charcateristics Specify the properties of the storage function , Examples of values are :

1、   sql security {definer|invoker}; Indicate who has authority to execute ;

        definer Indicates that only the definer can execute ;

        invoker Only the caller who has the right can execute , By default , The system is designated as definer;

2、   comment’string’: Annotation information , Can be used to describe storage functions .

The body of the function

① The function body is composed of SQL Code composition ;

② The body of a function can be simple SQL sentence , such as : Simple query statements

③ If the function body is a composite structure, you need to use begin…end sentence

④ Composite structures can contain declarations 、 Process control .

delimiter //          -- Set the terminator to //

create function ym_date(mydate date)

returns varchar(15)          -- returns Specifies the return type of the function

begin

return date_format(mydate,'%Y-%m');         -- The function needs to return a value ,return Return the corresponding processing result

end//

delimiter ;          -- Recovery Terminator

Delete custom function

drop function [if exists] func_name;

Variable : Can be stored in the program ( Stored procedures and functions ) Using variables in .

Grammar format :declare var_name[,var_name] … date_type [default value];

Two ways of assignment :

① Set var_name = expr[,var_name = expr]…;

② Select col_name[,…] into var_name[…] table_expr;

If Branch statement

if condition then

              ……;

[elseif condition then]

              ……;

[else]

              …;

end if;

case Branch statement

①        case case_expr

                when when_value then statement_list;

                [when when_value then statement_list;]…

                [else statement_list;]

            end case;

②        case

                when expr_condition then statement_list;

                [when expr_condition then statement_list;]…

                [else statement_list;]

             end case;

while Loop statement

Grammar format :        [while_label:]while condition do

                          …

                          End while[while_libe];

loop Loop statement : This loop has no built-in loop conditions , But it can go through leave Statement exit loop .

Grammar format :        [loop_label:]loop

                          Statement_list;

                          End loop [loop_label];

leave Statement is used to jump out of a loop , Grammar format :leave label;

repeat Loop statement : This statement executes a loop body , After judgment condition Is the condition true , If true, exit the loop , Otherwise, continue to execute the loop body .

Grammar format :        [repeat_label:] repeat

                          …;

                          until expr_condition

                          end repeat [repeat_label:];

stored procedure

The stored procedure is SQL A precompiled collection of statements and process control statements , It is stored with a name and processed as a unit .

Grammatical structure :        create procedure proc_name([proc_parameter])

                          [characteristics…] routine_body

proc_parameter Specifies the parameter list of the stored procedure , Form the following :

[in|out|inout] param_name type

in: The value representing the parameter must be specified when the stored procedure is called .

out: Indicates that the value of this parameter can be changed by the stored procedure , And you can go back to .

inout: Indicates the value of this parameter, which is specified when calling , And can be changed and returned .

The process of body (routine_body)

① The process body consists of legal SQL Sentence structure ;

② The process body can be arbitrary SQL sentence ;

③ If the process body is a composite structure, use begin…end sentence ;

④ Composite structures can contain declarations , Flow control statement .

Calling stored procedure

① call proc_name([parameter[,…]]);

② call proc_name[()];

Delete stored procedure

drop procedure [if exists] proc_name;

The difference between stored procedures and functions

1. function Differences on :

stored procedure : Generally speaking , The functions implemented by stored procedures are a little more complex . Powerful , You can perform a series of database operations including modifying tables .

Storage function : The functions implemented are highly targeted .

2. Return value Differences on :

stored procedure : Multiple values can be returned , You can also not return a value , Just to achieve an effect or action .

Storage function : Must have return value , And there can only be one return value .

3. Parameters Different :

stored procedure : There are three parameter types for stored procedures ,in、out、inout.

Storage function : There is only one parameter type , Be similar to in Parameters . When calling a function, you need to specify the value according to the type of the parameter .

4. Grammatical structure Differences on :

stored procedure : There is no need to specify the return type when declaring a stored procedure .

Storage function : When declaring a function, you need to specify the return type , And a valid... Must be included in the function body return sentence .

5. Call mode Differences on :

stored procedure : It is generally executed as a separate part , use call Call statement .

Storage function : Embedded in the sql Used in , Can be in select Call in .

MySQL The business of

A transaction consists of one or more SQL An integral whole of statements ,SQL Interdependence between statements , Or do it all , Or none of them .

Four conditions that a transaction must meet

atomicity( Atomicity )

consistency( Uniformity )

isolation( Isolation, )

durability( persistence )

Control transactions

1、rollback: Rolling back ends the user's transaction , And undo all pending changes .

2、commit: Will commit the transaction , And make all changes that have been made to the database permanent .

3、savepoint identifier: Allows creation of a savepoint in a transaction , There can be more than one... In a transaction savepoint.

4、rollback to identifier: Roll back the transaction to the marked point

mysql There are two main methods of transaction processing :

1、 use begin,rollback,commit To achieve

begin or start transaction Start a transaction

rollback Transaction rollback

commit Transaction confirmation

2、 Direct use set To change MySQL The auto submit mode of :

set autocommit = 0 Disable auto submit

set autocommit = 1 Turn on auto submit

innodb Is the preferred engine for transactional databases , Support transaction security (ACID).

example :

DELIMITER //

CREATE PROCEDURE borrowproc(cid CHAR(18),bid INT)

BEGIN

DECLARE store_num INT;

DECLARE money FLOAT(7,3);

SELECT store INTO store_num INTO bookinfo WHERE book_id = bid;

SELECT balance INTO money INTO readerinfo WHERE card_id = cid;

SET autocommit = 0;

INSERT INTO borrowinfo VALUES(bid,cid,CURDATE(),DATE_ADD(CURDATE(),INTERVAL 1 MONTH),' no ');

UPDATE bookinfo SET store = store - 1 WHERE book_id = bid;

UPDATE readerinfo SET balance = balance - (SELECT price FROM bookinfo WHERE book_id = bid) * 0.05 WHERE card_id = cid;

IF store_num = 0 OR money <= 200 THEN

              ROLLBACK;

ELSE

              COMMIT;

END IF;

END//

DELIMITER ;

The introduction of storage engine

Database storage engine is the underlying software component of database . Database management system uses data engine to create 、 Inquire about 、 Update and delete data .

MYSQL The core is the storage engine .

have access to show engines Statement to view the engine types supported by the system .

innodb Storage engine

①  innodb to mysql Provided with commit 、 Transaction safe storage engine with rollback and crash recovery capabilities .

②  It has good performance for dealing with huge amount of data .

③  innodb The storage engine supports foreign key integrity constraints .

④  innodb It is used in many large database sites that need high performance .

MyISAM Storage engine

MyISAM Has a higher insert 、 Query speed , Transaction is not supported .

memory Storage engine

① memory The storage engine stores the data in the table in memory , Does not query and reference other table data to provide quick access .

② Use mysql memory The starting point of the storage engine is speed . To get the fastest response time , The logical storage medium used is system memory . Although storing table data in memory does provide high performance , But when mysql When the daemon crashes , be-all memory Data will be lost . While acquiring speed, it also brings some defects .

Choice of storage engine

1、innodb: Offer to submit 、 Transaction security capabilities for rollback and crash recovery capabilities , Concurrency control can be realized .

2、myisam: Data table is mainly used to insert and query records , use myisam The engine can provide high processing efficiency .

3、memory: Temporary storage of data , Not a lot of data , And no need for high data security , You can choose to save the data in memory memory engine .

Set up the storage engine

1、 Set the storage engine of the server

In profile my.ini Medium [mysqld] Next, set the required storage engine :

default-storage-engine=innodb

restart mysql The server .

2、 Set the client's storage engine

set default_storage_engine = innodb;

3、 Set up the storage engine when creating tables

example :create table mytest(

       Id int primary key,

       name varchar(10)

       )engine = innodb default charset = utf8;

Look at the storage engine of the table :show table status from mydata where name ='myengine';

4、 Modify the storage engine of the table

alter table tablename engine = enginename;

mysql Management and maintenance of

mysql User management of :

              ①  root The user is a super administrator , Have all permissions .

              ②   Ordinary users only have various permissions granted .

Permissions on the table

Mysql The server controls the user's access to the database through the permission table , The authority list is stored in mysql In the database .

The permission information table of the storage account mainly includes :user、db、host、tables_priv、columns_priv and procs_priv.

Function of each permission table

1、user Table time mysql The most important permission table in , Record the account information allowed to connect to the server , The permissions in it are global .

2、db Table and host Table is mysql A very important permission table in data .

3、db The table stores the user's operation permissions on a database .

4、host The table stores the operation permissions of a host to the database .

5、tables_priv Table is used to set operation permissions on the table .

6、columns_priv Table is used to set permissions on a column of the table .

7、procs_priv Table can set operation permissions for stored procedures and stored functions .

Account management

New normal user

Create a new user , You must have appropriate permissions to perform the creation operation .

stay mysql In the database , have access to create user or grant sentence .

Basic grammar :

create user ‘user’@’host’                    -- host Refers to the host name

identified by [password] ‘password’

create user The new user created by the statement does not have any permissions , You also need to use grant Statement gives the user permission ; and grant Statement can not only create new users , You can also authorize users while creating .

Basic grammar :

grant privileges on db.table

to ‘user’@’host’ [identified by ‘password’];

Delete normal users

grammar :drop user user[,user];

example :drop user ‘testuser’@’localhost’;

grammar :delete from mysql.user where host=’hostname’ and user = ‘username’;

Permission management is mainly to log in to the mysql Verify the user's rights , The permissions of all users are stored in mysql In the permission table of .

mysql The main function of the permission system is to confirm the user connected to a host , And give the user various permissions on the database .

Grant permissions to users

Basic grammar :        grant priv_type on db.table to ‘user’@’host’

                          [identified by [password] ‘password’];

flush privileges;                              // Refresh the system permission table

Check the user's authorization

Basic grammar :show grants for ‘user’@’host’;

Take back authority

Grammar format :revoke privilege on db.table from ‘user’@’host’;

MySQL A log of MySQL Database status 、 The user action 、 Error messages, etc , It can be for MySQL Management and optimization provide the necessary information .

classification :

① Error log : Record mysql Start of service 、 To run or stop mysql Problems with service .

② Query log : Recorded mysql All user actions , Including starting and shutting down services 、 Execute queries and update statements .

③ Binary log : Record all statements that change data .

④ Slow query log : Record all execution times over long_query_time All queries of or queries without index .

Start and set the error log

By default , The error log will be recorded in the data directory of the database . If no file name is specified in the configuration file , The file name defaults to hostname.err.

Start and stop the error log and specify the log file name , Can be modified my.ini To configure the . The configuration item of the error log is log-error.

If you need to specify a file name , Then the configuration items are as follows :    [mysqld]                                                                                                                                              log-error=file_name

Check the error log

        mysql The error log is stored in text form , You can use a text editor to view mysql Error log for .

         If you don't know the storage path of the log file , have access to show variables Statement to query the storage path of the error log .

        show variables like ‘log_error’;

Delete error log

         If the database runs for a long time , The error log file may be large , Then you can delete the log file , Re create a new error log file .

        mysql The error log is stored in the file system as a text file , You can delete .

         After deleting the error log , If you need to rebuild the log file , You need to execute the following commands on the server side :mysqladmin –uroot –p flush-logs

Or log in mysql, And then execute flush logs sentence :

         When the log file does not exist , perform flush logs Statement will create a new log file .

         If the log file exists , Do not do log backup and creation .

Data backup

mysqldump yes mysql Provides a very useful database backup tool .

mysqldump When the order is executed , The database can be backed up as a text file .

Basic grammar :              mysqldump –u user –h host –p password

                                       dbname[tbname,[tbname…]]>filename.sql

example :mysqldump --no-defaults -uroot -p mydata > D:test.sql

Backup database table :

example :mysqldump --no-defaults -uroot -p mydata mytest >xxx.sql

Backing up multiple databases :

example :mysqldump --no-defaults -uroot -p --databases mydata mysql > xxx.sql

Back up all databases :

example :mysqldump --no-defaults -uroot -p --all-databases > xxx.sql

Recovery of data

Use mysql Order recovery , Grammar format :

mysql –u user –p [dbname] < filename.sql

If the login has not expired, the server , You can also use source Command import SQL file , grammar :source filename

export : Will be mysql The data in the database is exported to an external storage file .

Import : Is to import the data in the external storage file into mysql In the database .

Export of data table

Use select…into outfile Export text file , Grammar format :select columnlist from table where condition into outfile ‘filename’ [options]

[options] Is an optional parameter , such as :

①   Parameters fields terminated by ‘value’: Set the split character between fields , It can be single or multiple characters , Tab by default ’\t’.

②   Parameters lines terminated by ‘value’: Set the character at the end of each line of data , It can be single or multiple characters , Tab by default ’\n’.

File import and export path :

my.ini→ secure-file-priv="e"        // Appoint mysql Import / export path

secure-file-priv=null        // Limit mysql Import and export

secure-file-priv=’’            //mysql There are no restrictions on import and export

example :mysql> select * from mydata.classinfo into outfile '…/class.txt'

       -> fields terminated by ','

       -> lines terminated by '\r\n';

Use mysqldump Command to export a text file

Mysqldump Create a table containing create table Of the statement tablename.sql File and a file containing its data tablename.txt file .

Grammar format :mysqldump –T path –u root –p dbname [tables] [options]

[options] Is an optional parameter , such as :

1、--fields-terminated-by=value: Set the separator character between fields , It can be single or multiple characters , Tab by default ’\t’.

2、--lines-terminated-by=value: Set the character at the end of each line of data , It can be single or multiple characters , Tab by default ’\n’.

Use mysql Command to export a text file

Grammar format :mysql –u root –p --execute=”select sentence ” dbname > filename.txt

( There are more field names in the first line of the export file )

Import of data table

Use load data infile To import a text file , Grammar format :    load data infile ‘filename.txt’ into table tablename [options] [ignore number lines]

[options] Is an optional parameter , such as :

①   Parameters fields terminated by ‘value’: Set the split character between fields , Sure                                     For single or multiple characters , Tab by default ’\t’.

②   Parameters lines terminated by ‘value’: Set the character at the end of each line of data , It can be single or multiple characters , Tab by default ’\n’.

Use mysqlimport Command to import a text file

Grammar format :mysqlimport –u root –p dbname filename.txt [options]

[options] Is an optional parameter , such as :

1、--fields-terminated-by=value: Set the separator character between fields , It can be single or multiple characters , Tab by default ’\t’.

2、--lines-terminated-by=value: Set the character at the end of each line of data , It can be single or multiple characters , Tab by default ’\n’.

Add :

USE  Database name  :
Select the Mysql database , Use this command after all Mysql The commands are only for this database .

SHOW DATABASES:
List MySQL Database list of database management system .

SHOW TABLES:
Show all tables of the specified database , Use... Before using this command use Command to select the database to operate .

SHOW COLUMNS FROM  Data sheet :
Show properties of data table , Attribute types , Primary key information , Is it NULL, Default values and other information .

SHOW INDEX FROM  Data sheet :
Show detailed index information of data table , Include PRIMARY KEY( Primary key ).

SHOW TABLE STATUS [FROM db_name] [LIKE 'pattern'] \G:    The  The order will  transport  Out Mysql data  library  Management Department  system  Performance and  Statistics  Information .
#  add  \G, Query conclusion  The fruit is divided into columns  print 

UNION Operators are used to connect more than two SELECT The results of a statement are combined into a set of results .

UNION [ALL | DISTINCT]

DISTINCT:  Optional , Delete duplicate data in result set .

ALL:  Optional , Return all result sets , Contains duplicate data .

The percent sign is not used  %, LIKE Clause and equal sign  =  The effect is the same .

When the provided query criteria field is NULL when ,MySQL Three operators are provided :

  • IS NULL:  Current column value yes NULL, This operator returns true.
  • IS NOT NULL:  Current column value No by NULL, Operator return true.
  • <=>:  Than a The operator ( differ = Operator ), Dangbi a Two of value Equal or both by NULL when return true.

Business

stay MySQL Only use Innodb The database or table of the database engine supports transactions .

Indexes are divided into single column indexes and composite indexes

Single index , That is, an index contains only a single column , A table can have multiple single-column indexes .

Composite index , That is, an index contains multiple columns .

Create index

CREATE INDEX indexName ON table_name (column_name)

Modify table structure ( Add index )

ALTER table tableName ADD INDEX indexName(columnName)

Temporary tables are visible only in the current connection , When the connection is closed ,Mysql The table is automatically dropped and all space is freed .

If other MySQL Client connection MySQL Database server to create temporary tables , The temporary table is destroyed only when the client program is closed , Of course, it can also be destroyed manually .

 INSERT IGNORE INTO Data that already exists in the database will be ignored , If there is no data in the database , Just insert new data , If you have data, skip this data

see MySQL Installation directory and data storage directory

select @@basedir;             # The installation directory

select @@datadir;               # Data storage directory

show variables like '%secure%';      # see secure-file-priv value

MySQL Error exporting file , In case of an error “The MySQL server is running with the --secure-file-priv option so it cannot execute this statement”

find my.ini The configuration file , Search for secure, modify secure-file-priv route ( Notice slashes and backslashes ), restart MySQL service .

Use SELECT ... INTO OUTFILE Statement to export data

Set the specified format of data output through command options , The following example is an export CSV Format :

mysql> SELECT * FROM passwd INTO OUTFILE '/tmp/runoob.txt'
    -> FIELDS TERMINATED BY ',' [optionally] ENCLOSED BY '"'
    -> LINES TERMINATED BY '\r\n';

MySQL in delete where in Statement

原网站

版权声明
本文为[Maple forest]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221216095125.html