当前位置:网站首页>MySQL must know and learn

MySQL must know and learn

2022-07-06 19:36:00 Yingtai night snow

MySql Know and learn

To configure MySql

install mysql service

sudo apt update
sudo apt install mysql-server

see MySQL Is the installation successful

sudo systemctl status mysql

Set up MySQL Login password for

sudo mysql

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';

exit;

sudo mysql_secure_installation

load 《MySQL Will know 》 Routine for

Load into mysql

mysql -uroot -p

Create database

create database myMysql;

Import routines

use myMysql;
source +create.sql The address of 
source +populate.sql  The address of 

install mysql-workbench

Select the corresponding version in the official website mysql-workbeach, The installation package download address is as follows :https://dev.mysql.com/downloads/workbench/

sudo dpkg -i mysql-workbench-community_8.0.29-1ubuntu20.04_amd64.deb

If there is an error , execute

sudo apt -f install

Execute the first instruction after execution

PART4 Retrieving data

———SELECT Statement to retrieve one or more data columns

SELECT The statement must contain

  • The column name you want to select
  • Choose from that list

Retrieve a single column

SELECT prod_name FROM products;

matters needing attention :

multiple SQL Statement must be semicolon ; Division

SQL Although not case sensitive , But in the process of daily use, we need more SQL Keywords are capitalized , Use lowercase for all columns and indications .

SQL Spaces are automatically ignored ,SQL Commands can be given on one line or on multiple lines

Retrieve multiple columns

SELECT prod_id,prod_name,prod_price FROM products;

Retrieve all columns

SELECT * FROM products;

Retrieve different lines ( No duplicate values )

DISTINCT keyword : instructions MySQL Only different values are returned

SELECT DISTINCT vend_id FROM myMysql.products;

When using DISTINCT Keyword is applied to all columns of the selected table instead of the columns that precede it

Restrict the search results

SELECT prod_name FROM products LIMIT 3,4;
SELECT prod_name FROM products LIMIT 5;

Use keywords LIMIT Limit the number of output lines

When there are two parameters, the first starting position , The default from the 0 Start counting , The second parameter is the number of rows to get

When there is only one parameter, it defaults from 0 Start at j That's ok

PART5 Sorting and retrieving data

Use only SQL Statement returns a single column in a database table . If you don't make the order of sorting , The data is generally displayed in the order it appears in the underlying table . This order can be the order in which the data was originally added to the table , Or receive MySQL The impact of reusing reclaimed storage space .

In order to SELECT Statement to sort the retrieved data clearly , have access to ORDER BY Clause .

ORDER BY Clause takes the name of one or more columns , Sort the output accordingly

Clause == A keyword + The data provided consists of

Use ORDER BY Clauses are arranged in ascending order by default

Sorting data

SELECT prod_name FROM products ORDER BY prod_name;
SELECT prod_name FROM products ORDER BY prod_price;

The selected column can be used to display the selected column , You can also sort data using columns that are not retrieved

Sort by multiple columns

To sort by multiple columns , Just specify the column name , Separate column names with commas .

mysql> SELECT
    -> prod_id,prod_price,prod_name
    -> FROM products
    -> ORDER BY
    -> prod_price,prod_name;

Specify sorting direction

Use ORDER BY Sort the data , In order to Ascending sort is the default sort order . With DESC Specify descending operations

mysql> SELECT
    -> prod_id,prod_price,prod_name
    -> FROM products
    -> ORDER BY
    -> prod_price DESC;

Sort multiple columns

SELECT prod_id,prod_price,prod_name FROM myMysql.products order by prod_price desc,prod_name desc;

If you want to perform descending operations on multiple columns , You must specify... For each column DESC keyword

utilize ORDER BY and LIMIT The combination of , Can find the highest or lowest value in a column , But we need to pay attention LIMIT Must be in ORDER BY Behind

select prod_id,prod_price,prod_name from myMysql.products order by prod_price desc limit 1;

PART6 Filtering data

search criteria ( Filter conditions ): To retrieve only the required data, you need to specify search criteria

SELECT In the sentence , The data is based on WHERE Filter the search criteria specified in clause .WHERE Clause in table name (FROM Clause ) Then give

select prod_name ,prod_price
from myMysql.products
where prod_price=2.50;

WHERE Clause and ORDER BY When clauses are used at the same time , Should let ORDER BY be located WHERE after

MySQL Case insensitive by default when matching

IS NULL Clause can be used to check by default that there is NULL Columns of values

select cust_id 
from myMysql.customers
where cust_email is null;

PART7 Data filtering

MySQL Allow multiple WHERE Clause . These clauses are used in two ways , With AND The manner of clause or OR The way clause

The operator ( Logical operators ): Used to connect or change WHERE The keyword of a clause in a clause .

select prod_id,prod_price,prod_name
from myMysql.products
where vend_id=1003 and prod_price<10;

AND: Use in WHERE clause Key words of , Used to indicate the retrieval of rows that satisfy all given conditions

OR: instructions MySQL Retrieve matching any condition

because SQL Processing OR Before the operator , Will deal with Limited AND character . So use parentheses to explicitly group the corresponding operators

IN: Used to specify the condition range , Each condition in the scope can be matched .IN Comma separated list of valid values , All enclosed in parentheses

select prod_id,prod_price,prod_name
from myMysql.products
where vend_id in (1002,1003) 
order by prod_name;

IN WHERE Clause to specify the list of values to match , Function and OR Quite a

NOT : Any condition following negation

select prod_id,prod_price,prod_name
from myMysql.products
where vend_id not in (1002,1003) 
order by prod_name;

PART8 Filter with wildcards

The previous operators filter for known values . But this method is not always easy to use . Wildcards can be used to create search patterns that compare specific data .

wildcard : A special character used to match a part of a value

search mode : Literal value 、 Wildcards or a combination of the two make up the search criteria .

When using wildcards , You have to use LIKE The operator .LIKE instructions MySQL, The following search patterns are compared using wildcard matching instead of direct equal matching .LIKE It's a predicate .

Percent sign % wildcard

% Means any character appears any number of times

select prod_id,prod_name
from myMysql.products
where prod_name like 'jet%';

Wildcards can be used anywhere in the search pattern , And you can use multiple wildcards

select prod_id,prod_name
from myMysql.products
where prod_name like '%anvil%';

Wildcards can also appear in the middle of the search pattern

select prod_id,prod_name
from myMysql.products
where prod_name like 'j%k%';

When using wildcards, trailing spaces may interfere with wildcard matching , Therefore, you can add one at the end of the search mode %, Or use functions

Wildcards cannot match NULL

Underline _ wildcard

The underscore wildcard matches only a single character, not multiple characters

select prod_id,prod_name
from myMysql.products
where prod_name like '_ ton anvil';

PART9 Search with regular expressions

Regular expressions are used to match specific strings of text ( Character set )

MySQL use WHERE Clause provides preliminary support for regular expressions , Allows you to specify regular expressions , Filter SELECT Retrieved data .

Basic Regular Expression

REGEXP What follows is treated as a regular expression

select prod_id,prod_name
from myMysql.products
where prod_name regexp '1000'
order by prod_name;

. To match any character

And LIKE Compare

LIKE Match the entire column . If the matched text appears in the column value ,LIKE It will not be found , The corresponding line is not returned ( Unless you use wildcards )

REGEXP Match within column values , If the matched text appears in the column value ,REGEXP Will find it , The corresponding line is returned

select prod_id,prod_name
from myMysql.products
where prod_name like '1000'
order by prod_name;


select prod_id,prod_name
from myMysql.products
where prod_name regexp '1000'
order by prod_name;

Conduct OR matching

Multiple OR Conditions can be merged into a regular expression

select prod_id,prod_name
from myMysql.products
where prod_name regexp '1000|2000'
order by prod_name;

Match one of several characters

You can use a set of [ and ] Enclosed characters to complete , [] It's another form of OR sentence

select prod_id,prod_name
from myMysql.products
where prod_name regexp '[123] Ton'
order by prod_name;

Character sets can be negated , They will match anything except the specified characters . To negate a character set , Place a... At the beginning of the collection ^ that will do

Match range

have access to - Define a scope

select prod_id,prod_name
from myMysql.products
where prod_name regexp '[1-4] Ton'
order by prod_name;

Match special character

To match special characters , Must use \ \ As the leader . \ \ - Expression lookup -,\ \ . Expression lookup .

select prod_id,prod_name
from myMysql.products
where prod_name regexp '\\.'
order by prod_name;

In the process of string matching , You can use predefined strings , Called string class

Match multiple instances

select prod_id,prod_name
from myMysql.products
where prod_name regexp '\\([0-9] sticks?\\)'
order by prod_name;
select prod_id,prod_name
from myMysql.products
where prod_name regexp '[[:digit:]]{4}'
order by prod_name;

Locator

Match text at a specific location , Use locators

select prod_id,prod_name
from myMysql.products
where prod_name regexp '^[0-9\\.]'
order by prod_name;

^ There are two uses , In the assembly , Use it to negate the set , otherwise , Used of the beginning of a string .

PART10 Create calculated fields

Calculated fields do not actually exist in the database . The calculation field is run at SELECT Created in statement

Field : The meaning is the same as column , In database, columns are generally called columns , The term field is usually used to calculate the connection of the field

Only the database knows SELECT Those columns in the statement are the actual table columns , Those columns are calculated fields . From the client ( Applications ) From the perspective of , The data of the calculated field is returned in the same way as the data of other columns

Splicing field

Splicing : Join values together to form a single value

MySQL Of SELECT In the sentence , You can use Concat() Function to splice two columns

Concat(): Connect multiple strings to form a long string

Concat() One or more specified strings are required , The strings are separated by commas

select concat(vend_name,'(',vend_country,')')
from myMysql.vendors
order by vend_name;

Use RTrim() Function can delete the extra space on the right side of the data to sort out the data

select concat(rtrim(vend_name),'(',rtrim(vend_country),')')
from myMysql.vendors
order by vend_name;

LTrim() Remove the space to the left of the string

Trim() Remove the spaces on the left and right sides of the string

Use the alias

Alias : Is an alternative name for a field or value . It's called AS Key words are given to

select concat(rtrim(vend_name),'(',rtrim(vend_country),')') as vender_title
from myMysql.vendors
order by vend_name;

Perform arithmetic calculations

It can perform simple arithmetic calculation on the retrieved data

select prod_id,quantity,item_price,
	quantity*item_price as expanded_price
from myMysql.orderitems
where order_num=20005;

PART11 Using data processing functions

Functions generally execute on data , It provides convenience for data conversion and processing

According to the function of the function, it can be divided into

  • Text processing function
  • Date processing function
  • Numerical processing function
select vend_name,upper(vend_name)as vend_name_upper
from myMysql.vendors
order by vend_name;
select cust_name,cust_contact
from myMysql.customers
where soundex(cust_contact)=soundex('y. lie');
select cust_id,order_num
from myMysql.orders
where date(order_date)='2005-09-01';
select cust_id,order_num,order_date
from myMysql.orders
where date(order_date) between '2005-09-01' and '2005-09-30';

select cust_id,order_num,order_date
from myMysql.orders
where year(order_date)=2005 and month(order_date)=9;
select cust_id,order_num,order_date,mod(order_num,3)as modValue
from myMysql.orders
where year(order_date)=2005 and month(order_date)=9;

PART12 Summary data

Focus function : Run on line group , Functions that calculate and return individual values

AVG function

AVG() By counting the number of rows in the table and calculating the value of specific columns , Find the average value of this column .AVG() Can be used to return the average of all columns , You can also return the average value of the specified column or row

  • AVG() It can only be used to determine the average of a particular numeric column , And the column name must be given as a function parameter
  • To get the average of multiple columns , You have to use multiple AVG() function
  • AVG() Function ignores column values as NULL The line of
select avg(prod_price) as avg_price
from myMysql.products;
select avg(prod_price) as avg_price
from myMysql.products
where vend_id=1003;

COUNT function

coun() Determine the number of rows in the table or the number of rows that meet certain criteria

  • count(*) Count the number of rows in the table , Whether the table column contains control (NULL) Or non null
  • Use count(column) Count rows with values in a specific column , Ignore NULL value
select count(*) as count_num
from myMysql.products;
select count(vend_id) as count_num
from myMysql.products;

MAX function

  • max() Returns the maximum value in the specified column
  • When applied to text data , If the data is sorted by the corresponding column , be MAX() Go back to the last line
  • MAX() Function ignores column values as NULL The line of
select max(vend_id) as max_num
from myMysql.products;

MIN function

  • Returns the minimum value of the specified column
  • When applied to text data , If the data is sorted by the corresponding column , be MIN() Go back to the first line
  • Ignore column values as NULL The line of
select min(prod_name) as max_num
from myMysql.products;

SUM function

  • Used to return the sum of the specified column values
  • It can also be used to sum up the calculated value
  • Ignore column values as NULL The line of
select sum(quantity) as items_ordered
from myMysql.orderitems
where order_num=20005;
select sum(quantity*item_price) as total_price
from myMysql.orderitems
where order_num=20005;

Cluster different values

  • Perform calculations on all rows , Appoint ALL Parameters or no parameters ( because ALL It's the default behavior )
  • Contains only different values , Appoint DISTINCT Parameters
select avg(distinct prod_price) as avg_price
from myMysql.products
where vend_id=1003;

If you specify a column name , be distinct It can only be used for count().distinct Cannot be used for count(*)

Combined clustering function

SELECT The statement can contain multiple focus functions as needed

select avg(distinct prod_price) as avg_price,
		count(*) as num_items,
        min(prod_price)as price_min,
        max(prod_price)as price_max,
        avg(prod_price)as price_avg,
        sum(prod_price)as price_sum
        
from myMysql.products;

PART13 Grouped data

grouping : Allows data to be divided into logical groups , So that each group can be clustered

The group is in SELECT Of the statement GROUP BY Clause

select vend_id,count(*)as num_prods
from myMysql.products
group by vend_id;

Use GROUP By, It is not necessary to specify each group to be calculated and valued . The system will automatically complete .GROUP BY Clause indicates MySQL Grouped data , Then aggregate each group instead of the entire result set .

Filter grouping

MySQL Allow filtering groups , The rules include those groups , Exclude those groups . It must be filtered based on complete groupings rather than individual rows .

HAVING Clause , Can be used as an alternative WHERE Clause , The only difference is ,WHERE Filter line ,HAVING Filter grouping

select vend_id,count(*)as num_prods
from myMysql.products
group by vend_id
having count(*)>2;

Filtering is based on grouping aggregate values rather than specific row values

WHERE Filter before data grouping ,HAVING Filter after data grouping .WHERE Excluded rows are not included in the group , This may change the calculated value , Thereby affecting HAVING Groups filtered out in Clauses based on these values

WHERE and HAVING The combination of clauses

select vend_id,count(*)as num_prods
from myMysql.products
where prod_price>=10
group by vend_id
having count(*)>=2;

Execute first where Clause filters out all prod_price At least for 10 The line of , Then perform grouping and filtering

In the use of GROUP BY When clause , Should also give ORDER BY Clause , This is the only way to ensure that the data is sorted correctly .

select order_num,sum(quantity*item_price)as ordertoal
from myMysql.orderitems
group by order_num
having sum(quantity*item_price)>=50;
select order_num,sum(quantity*item_price)as ordertoal
from myMysql.orderitems
group by order_num
having sum(quantity*item_price)>=50
order by ordertoal;

PART14 Use subquery

Inquire about , whatever SQL Statements are all query operations .

Subquery , Queries nested in other queries

Subqueries can combine multiple queries into one statement . It has two ways

  1. Use subqueries to filter
  2. Use subqueries as calculation fields
select order_num
from myMysql.orderitems
where prod_id='TNT2';


select cust_id
from myMysql.orders
where order_num in (20005,20007);

select cust_name,cust_contact
from myMysql.customers
where cust_id in (10001,10004);


# Operations using subqueries 
select cust_name,cust_contact
from myMysql.customers
where cust_id in(
	select cust_id
	from myMysql.orders
	where order_num in (
		select order_num
		from myMysql.orderitems
		where prod_id='TNT2'
	)
);

In actual use , Due to the limitation of computer performance , Therefore, you cannot nest too many subqueries

select cust_name,cust_state,
(select count(*)
from myMysql.orders
where orders.cust_id=customers.cust_id)as orders
from myMysql.customers
order by cust_name;

Correlation subquery : Subqueries involving external queries

At any time when the column name may exist, there is ambiguity , You have to use this grammar ( Table and column names are separated by a period )

PART15 Join table

SQL One of the most powerful functions is the ability to use join tables in the execution of data retrieval queries

The design of relational table is to ensure that the information is decomposed into multiple tables , One table for a class of data . Each table passes through some commonly used values ( That is, the relationship in relationship design ) They are related to each other

Foreign keys : The foreign key is a column in a table , It contains the primary key value of another table , Defines the relationship between two tables

  • Information will not repeat , Thus, space and time will not be wasted
  • When the data changes , Just change a single record
  • Data processing becomes simpler

Scalability , Able to adapt to the increasing workload without failure . A well-designed database or application is called scalable

Relational data can be effectively stored and easily processed , Therefore, the scalability of relational database is better than that of non relational database

When data is stored in multiple tables , How to use a single SELECT Statement to retrieve data ?

-> Use connection . Connection is a mechanism , Used in a SELECT Statement , Therefore, it is called connection . Use special syntax , Multiple tables can be joined to return a set of outputs , Joins the correct rows in the runtime association table

coupling , It's not a physical entity , It doesn't exist in the actual database table , The connection consists of MySQL Establish... As needed , It exists in the execution of the query

select vend_name,prod_name,prod_price
from myMysql.vendors,myMysql.products
where vendors.vend_id=products.vend_id
order by vend_name,prod_name;

The referenced column may be ambiguous , You must use a fully qualified column name ( Table and column names separated by a dot )

In one SELECT When joining several tables in a statement , The corresponding relationship is constructed in operation . In the definition of database table, there is no such thing as MySQL How to join tables

The cartesian product ( Fork connection ): The result returned by a table relation without a join condition is a Cartesian product . The number of rows retrieved will be the number of rows in the first table times the number of rows in the second table

Use internal connections

select vend_name,prod_name,prod_price
from vendors inner join products
on vendors.vend_id=products.vend_id
order by vend_name,prod_name;

Join multiple tables

select vend_name,prod_name,prod_price,quantity
from myMysql.vendors,myMysql.products,myMysql.orderitems
where products.vend_id=vendors.vend_id
	and orderitems.prod_id=products.prod_id
    and orderitems.order_num=20005
order by vend_name,prod_name;
select cust_name,cust_contact
from myMysql.customers
where cust_id in(
	select cust_id
	from myMysql.orders
	where order_num in (
		select order_num
		from myMysql.orderitems
		where prod_id='TNT2'
	)
);


select cust_name,cust_contact
from customers,orders,orderitems
where customers.cust_id=orders.cust_id
	and orders.order_num=orderitems.order_num
    and prod_id='TNT2';

PART16 Create advanced Links

Aliases are used in addition to column names and calculated fields ,SQL It is also allowed to alias table names , It can

  • To shorten the SQL sentence
  • Allowed in single item SELECT Statement using the same table more than once
select cust_name,cust_contact
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id
	and o.order_num=oi.order_num
    and oi.prod_id='TNT2';

Table aliases can be used not only for where Clause , It can also be used for select The train ,order by Clause and the rest of the statement .

Table aliases are used only during query execution . Different from the column name , Table aliases are not returned to the client

Self coupling

select cust_name,cust_contact
from customers,orders,orderitems
where customers.cust_id=orders.cust_id
	and orders.order_num=orderitems.order_num
    and prod_id='TNT2';

select cust_name,cust_contact
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id
	and o.order_num=oi.order_num
    and oi.prod_id='TNT2';

Self join is usually used as an external statement instead of a subquery statement used to retrieve data from the same table . Although the final result is the same , But sometimes processing joins is much faster than processing subqueries

natural join

Natural connections exclude multiple occurrences , Make each column return only once . By using wildcards on the table (SELECT *), Use explicit subsets for all other table columns

select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id
	and oi.order_num=o.order_num
    and prod_id='FB';

outer join

A join contains rows that have no associated rows in the related table , This type of connection is called an external connection

select customers.cust_id,orders.order_num
from customers inner join orders
on customers.cust_id=orders.cust_id;

select customers.cust_id,orders.order_num
from customers left outer join orders
on customers.cust_id=orders.cust_id;

select customers.cust_id,orders.order_num
from customers right outer join orders
on orders.cust_id=customers.cust_id;

In the use of outer join Grammatical time , You have to use right perhaps left Keyword specifies a table that includes all its rows ,right Pointed out that outer join Table on the right , and left It is pointed out that outer join The table on the left

Left outer connection and right outer connection , The only difference between them is the order of the associated tables . The left outer link can be reversed from or where The order of the tables in the clause is converted to the right outer join . Therefore, the two types of external connections can be used with each other

Using joins with aggregate functions

select customers.cust_name,customers.cust_id,
	count(orders.order_num)as num_ord
from customers inner join orders
on customers.cust_id=orders.cust_id
group by customers.cust_id;

select customers.cust_name,customers.cust_id,
	count(orders.order_num)as num_ord
from customers left outer  join orders
on customers.cust_id=orders.cust_id
group by customers.cust_id;

Precautions for connection

  • Note the type of connection provided , Internal connections are generally used , But using external connections also needs to be effective
  • Make sure you use the correct connection conditions , Otherwise, incorrect data will be returned
  • You should always provide the connection conditions , Otherwise, we get Cartesian product
  • Multiple tables can be included in a join , Even different join types can be used for each join .

PART17 Combination query

MySQL Allow multiple queries ( multiple SELECT sentence ), And return the result as a single query result set . These queries are often referred to as join or compound query operations

  • Return similar structured data from different tables in a single query
  • Multiple queries on a single table , Return data by single query

Most of the time , Combining two queries of the same table does the same job as having pairs where A single query with Clause conditions does the same thing . namely , Any with multiple where Clause SELECT Statements can be given as a combined query

have access to UNION Operator to combine several SQL Inquire about . utilize UNION, More than one... Can be given SELECT sentence , Combine their results into a single result set

select vend_id,prod_id,prod_price
from products
where prod_price<=5
union
select vend_id,prod_id,prod_price
from products
where vend_id in(1001,1002);
  • union There must be two or more select Sentence composition , Use related words between sentences union Separate
  • union Each query in must contain the same columns 、 Expression or aggregate function
  • Column data must be compatible

union Duplicate rows are automatically removed from the query result set , This is a union Default behavior of , If you want to return all matching rows , You can use union all

select vend_id,prod_id,prod_price
from products
where prod_price<=5
union all
select vend_id,prod_id,prod_price
from products
where vend_id in(1001,1002);

union all by union A form of , It's done where What can't be done . If you really need all the matching lines of each record to appear ( Include Duplicate lines ), Must be used union all, But can't use where

In the use of union When combining queries , Only one... Can be used order by Clause , It must appear in the last select After statement , Multiple... Are not allowed order by Clause

select vend_id,prod_id,prod_price
from products
where prod_price<=5
union all
select vend_id,prod_id,prod_price
from products
where vend_id in(1001,1002)
order by vend_id,prod_price;

PART18 Full text search

When using full-text search ,MySQL You don't need to view each row separately , There is no need to analyze and process each word separately .MySQL Creates an index for each word in the specified column , Search can be done for these words . such MySQL Can quickly and effectively determine which words match , Which words don't match , Their matching frequency

Use full text search , The column to be searched must be indexed , And keep re indexing as the data changes . After properly designing the table ,MySQL All indexing and re indexing will be performed automatically . After index ,SELECT But with Match() and Against() Use together to actually perform a search

Enable full text search support

Generally, full-text search is enabled when creating tables .CREATE TABLE Statement acceptance FULLTEXT Clause , It gives a comma separated list of indexed values

create table  mydata
(	
	note_id int not null auto_increment,
    prod_id char(10) not null,
    noe_data datetime not null,
    note_text text null,
    primary key(note_id),
    fulltext(note_text)
)engine=MyISAM;

For full-text search ,MySQL According to the clause FULLTEXT(note_text) Index it according to the instructions of .FULLTEXT Index a single column , Multiple columns can be specified if necessary

After definition ,MySQL Automatically maintain the index . On the increase 、 Updating or deleting rows is , The index is automatically updated .

You can specify... When creating a table FULLTEXT, Or specify later
If you are transferring data to a new table , All data should be imported first , Then modify the table , Definition FULLTEXT, This helps to import data faster .

Do a full-text search

Match() Specify columns to search for ,Against() Specify the search expression to use .

select note_text
from productnotes
where match(note_text) against('rabbit');
  • Pass to Match() The value of must match FULLTEXT() Same in definition . If more than one column is specified , They must be listed
  • Search is case insensitive

use like Statement can complete similar operations

select note_text
from productnotes
where note_text like '%rabbit%';

Use like Return data in a less useful order , Use full-text search to return data sorted by the good degree of text matching

An important part of full-text search is to sort the results . Lines with higher registration return first .

select note_text,match(note_text) against('rabbit') as ranks 
from productnotes;

The ranking is mySQL According to the number of words in the line 、 Number of unique words 、 The total number of words in the whole index and the number of lines containing the word are calculated

When specifying multiple search terms , Those rows that contain most matching words have fewer words than ( Or only one match ) The higher level value of those lines

Use query extension

Query extensions are used to try to widen the range of full-text search results returned . When using query extensions ,MySQL Scan the data and index twice to complete the search

  • First , Conduct a basic full-text search , Find all rows that match the search criteria
  • secondly ,MySQL Check these matching lines and select all useful words
  • thirdly ,MySQL Full text search again , This time, we will not only use the original year , And use all the useful words

Expand with query , Be able to find possible relevant results , Even if they don't exactly contain the word they're looking for .

select note_text
from productnotes
where match(note_text) against('anvils' with query expansion);

Query expansion greatly increases the number of rows returned , But this also increases the number of rows that are actually not needed . The more rows in the table , The better the result returned by using query extension .

Use Boolean search

Boolean mode can provide

  • Words to match
  • Words to exclude
  • Arrangement hint
  • Expression grouping
  • Other things

Boolean method, even if it is not defined FULLTEXT Indexes , You can also use it .

select note_text
from productnotes
where match(note_text) against('heavy' in boolean mode);
select note_text
from productnotes
where match(note_text) against('heavy -rope*' in boolean mode);

- Exclude a word ,* Truncation operation ( It can be imagined as a wildcard used for the suffix )

select note_text
from productnotes
where match(note_text) against('+rabbit +bait' in boolean mode);

+ contain , Words must exist

select note_text
from productnotes
where match(note_text) against('rabbit bait' in boolean mode);

No operator specified , Then as long as there is one

select note_text
from productnotes
where match(note_text) against('"rabbit bait"' in boolean mode);

Match the phrase in double quotation marks , Not words

select note_text
from productnotes
where match(note_text) against('>rabbit <carrot' in boolean mode);

Increase the level of the former , Lower the level of the latter

select note_text
from productnotes
where match(note_text) against('+safe +(<combination)' in boolean mode);
  • When indexing full-text data , Short words ignored and excluded from index . Short words are defined as those with 3 Or 3 A word with a few characters

  • MySQL With a built-in list of non words , These words are always ignored when indexing full-text data . if necessary , You can override this list

  • When many words appear frequently , Searching for them is useless .MySQL There's a rule 50% The rules , If a word appears in 50% In the above lines , Regard it as an unusual word and ignore .50% Rule not used for in boolearn

  • If the number of rows in the table is less than 3 That's ok , Full text search does not return results

  • Ignore single quotes in words

  • Languages without word separators cannot properly return full-text search results

PART19 insert data

insert For insertion ( Or add ) Row to database table . Insertion can take the form of :

  • Insert full row
  • Insert part of row
  • Insert multiple rows
  • Insert the results of some queries

Insert full row

Use basic insert grammar , It requires specifying the table name and the value to be inserted into the new row

insert into customers
values (
	null,
    'pep E.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'USA',
    null,
    null
    );
    
    select *
	from customers;

above SQL Statements are highly dependent on the order in which the columns in the table are defined , And it also depends on the information that is easily available in its order . Even if this order information is available , There is no guarantee that the columns will remain exactly the same after the next table structure change order , To do this, click Edit

insert into customers(
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country,
    cust_contact,
    cust_email
)


values (
    'E.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'USA',
    null,
    null
    );
    
    select *
	from customers;

Because the column name is provided ,VALUES Must be Its specified order matches the specified column name , Not necessarily in the order in which the columns appear in the actual table . Its advantages are , Even if the structure of the table changes , here insert The statement still works correctly .

insert into customers(
    cust_country,
    cust_contact,
    cust_email,
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip
)


values (
	   'CHINA',
		null,
		null,
    'E.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046'
    );
    
    select *
	from customers;
-- -- 

Generally do not use a list that is not explicitly listed to get INSERT sentence . Using a list of columns enables SQL The code continues to work , Even if the table structure changes .

No matter which INSERT grammar , Must give VALUES The correct number of

If the definition of the table allows , Can be in INSERT Omit some columns in the operation . The omitted column must meet one of the following conditions

  • This column is defined to allow NULL value ( No value or null value )
  • Give default values in the table definition , This means that if you don't give a value , Double defaults will be used

Insert multiple rows

You can use more than one INSERT sentence , Even submit them once , Each statement ends with a semicolon

insert into customers(
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country
)


values (
    'KE.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'CHINA'
    );
insert into customers(
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country
)


values (
    'GE.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'CHINA'
    );
    
    select *
	from customers;
-- 
    

Or you can use composite statements

insert into customers(
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country
)


values (
    'KE.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'CHINA'
    ),
    (
    'GE.LaPew',
    '100 Main Street',
    'Los Angeles',
    'CA',
    '90046',
    'CHINA'
    );
    
    select *
	from customers;
-- -- 
    

Insert retrieved data

You can put one SELECT The result of the statement is inserted into the table , namely INSERT SELERT

insert into customers(
	cust_id,
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country
)
select 
	cust_id,
	cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country
from custnew;
-- -- 
   

insert select in select A statement can contain WHERE Clause can filter the inserted data

PART20 Update and delete data

Update data

To update ( modify ) Table data , have access to update sentence , There are two ways to use update

  • Update specific rows in the table
  • Update all rows in the table

Basic update The statement consists of the following 3 Part of it is made up of

  • Table to update
  • Column names and their new values
  • Make sure you want to update the filter criteria for the row
update customers
set cust_email='[email protected]'
where cust_id=10011;

set The command is used to assign the mind to the updated column , without where Clause ,MySQL All corresponding rows in the table will be updated with this value

Update all lines

update customers
set cust_email='[email protected]',cust_name='sxyc'
where cust_id=10011;

update You can use subqueries in statements , Make it possible to use SELECT The data retrieved by the statement updates the column data

If the update Statement update multiple lines , And an error occurs when updating one or more of these rows , Then the whole update The operation will be cancelled . But even if something goes wrong , You can also continue to update , You can use ignore keyword

update ignore customers

In order to delete the value of a column , You can set it to NULL, If the table definition allows NULL value

update customers
set cust_email=null
where cust_id=10011;

Delete data

To delete data from a table , Use delete sentence , There are two ways to use delete

  • Delete specific rows from the table
  • Delete all rows from the table
delete from customers
where cust_id=10011;

delete Delete entire rows instead of columns . To delete the specified column , You can use update sentence

delete Statement to delete a row from a table , Even delete all rows in the table , however delete Cannot delete table itself

If you want to delete all rows from the table , You can use truncate table, It's faster , It's actually deleting the original table and re creating a table , Instead of deleting the data in the table row by row

If you omit where Clause , be update or delete Will be applied to all rows in the table

PART21 Create and manipulate tables

MySQL Not only for table data manipulation , It can also be used to perform primitive operations on databases and tables , Including the creation and processing of the table itself

  • Use tools with interactive creation and management of tables
  • Tables can also be used directly MySQL Statement manipulation

The program creates a table , Use SQL Of create table sentence ,

Table creation foundation

Use create table Create table , The following information must be given

  • Name of the new table , In keywords create table Then give
  • Table column names and definitions , Split with a comma

create table Statements may also include other keywords or options , But at least include the name of the table and the details of the column

Each column is defined by column name ( He is the only one in the list ) Start , The data type followed by the column . The primary key of a table can be used when creating a table primary key Keyword assignment .

When creating a new table , The specified table name must not exist , Otherwise, it will be wrong . If you want to place an accidental overwrite of an existing table ,SQL It is required to delete the table first , Then rebuild it . If you want to set up a table to create it when it doesn't exist , It should be given after the table if not exists.

null Value means no value or missing value . allow NULL A value column is also allowed to insert a row without giving the value of the column . Don't allow NULL A column with a value does not accept rows with no value in the column , let me put it another way , When inserting or updating rows , This column must have a value

NULL It's not worth it , But it's not an empty string . Empty string is a valid value , It's not worthless

The primary key must be unique , Each row in a table must have a unique primary key value . If the primary key USES a single column , Its value must be unique . If you use multiple columns , Then the combined values of these columns must be unique

To create a primary key consisting of multiple columns , Column names should be given in a comma separated list

The primary key is the column that uniquely identifies each row in the table . Can only be used in primary key, not allowed NULL Columns of values . allow NULL The column of the value cannot be used as a unique identity

auto-increment tell MySQL, This column will be automatically incremented whenever there is a row earlier . One at a time INSERT In operation ,MySQL Automatically increment the column , Assign this value to the next available value . In this way, each row is assigned a unique cust_id, This can be used as the primary key value

Only one is allowed per table auto-increment Column , And it must be indexed

Cover auto-increment: It can be simple in insert Specify a value in the statement , As long as it is unique , This value will be used to replace the automatically generated value

determine auto-increment value ,MySQL The determination of auto generated components cannot know the specific value , You can use select last_insert_id() Go back to the last auto-increment value , Then use it for subsequent MySQL sentence

MySQL It is allowed to specify the default value used for this matter , Default value CREATE TABLE In the column definition of the statement DEFAULT Keyword assignment

MySQL Functions are not allowed as default values , It only supports constants

MySQL With multiple engines . It packages multiple engines , These engines are hidden in MySQL In server . Different engines have different functions and characteristics , Choosing the right engine for different tasks can get good function and flexibility .

If omitted ENGING= sentence , You can use the default engine , The approximate rate is MyISAM

  • InnoDB, Is a reliable transaction engine , Full text search is not supported
  • MEMORY Functionally equivalent to MyISAM, But because the data is stored in memory ( Not disk ) in , fast ( Especially suitable for temporary tables )
  • MyISAM It's a very high performance engine , It supports full-text search , Transaction is not supported

Foreign keys cannot cross engine , That is, tables using one engine cannot reference foreign keys with tables using different engines

Update table

have access to ALTER TABLE sentence , Follow your watch

  • stay ALTER TABLE Then give the table name to be changed
  • List of changes made
alter table vendors
add vnd_phone char(20);
alter table orderitems
add constraint fk_orderitems_orders
foreign key (order_num)
references orders(order_num);

ALTER TABLE The common use of is to define foreign keys

  • Create a new table with a new column layout
  • Use insert select Statement to copy data from the old table to the new table . If necessary , Conversion functions and calculation characters can be used
  • Verify the new table containing the required data
  • Rename old table
  • Rename the new table with the original name of the old table
  • According to need , Recreate trigger , stored procedure , Indexes and foreign keys

Delete table

Use DROP TABLE Statement can realize

rename table

Use RENAME TABLE Statement can rename a table

PART22 Try to use

View It's a virtual table , Not the same as the table containing the data , Views only contain queries that retrieve data dynamically when in use .

As a view , It does not contain any columns or data that should be in the table , It contains a SQL Inquire about

The function of view :

  • Can be repeated SQL sentence
  • Simplify complex SQL operation
  • Use parts of the table instead of the entire table
  • Protection operation
  • Change data format and presentation

After the view is created , They can be used in much the same way as tables . Can execute on view SELECT operation , Filtering and sorting data , Join a view to another view or table , You can even add and change data

Driving in is just a facility for viewing data stored elsewhere . The view itself does not contain data , Therefore, the returned data is retrieved from other tables . When adding or changing data in these tables , The view will return the changed data

Rules and restrictions for views

  • Views must be uniquely named
  • There is no limit to the number of views that can be created
  • To create a view , You must have sufficient permissions
  • Views can be nested , You can use queries that retrieve data from other views to construct a view
  • order by Use in view , But if you retrieve data from a view select The statement also contains order by, Then order by Will be overwritten
  • View cannot be indexed , Nor can it be associated with triggers or default values
  • Views can be used with tables
create view productcustomers as 
select cust_name,cust_contact,prod_id
from customers,orders,orderitems
where customers.cust_id=orders.cust_id
	and orderitems.order_num=orders.order_num;


select *
from productcustomers
where productcustomers.prod_if='TNT2';
select concat(rtrim(vend_name),'(',rtrim(vend_country),')')
from myMysql.vendors
order by vend_name;


create view vendorlocation as
select concat(rtrim(vend_name),'(',rtrim(vend_country),')')
from myMysql.vendors
order by vend_name;

select * 
from vendorlocation;
create view customeremaillist as 
select cust_id,cust_name,cust_email
from customers
where cust_email is not null;

select *
from customeremaillist;
select prod_id,quantity,item_price,
	quantity*item_price as expanded_price
from myMysql.orderitems
where order_num=20005;

create view orderitemsexpanded as
select order_num,prod_id,quantity,item_price,
	quantity*item_price as expanded_price
from myMysql.orderitems;

select *
from orderitemsexpanded
where order_num=20005

stay MySQL When processing this query , It will specify where Clause added to the view query where Clause , In order to filter the data correctly

Using views , Basic can be written at one time SQL, Then use it many times as needed

A where Clause ,, Then these two groups of clauses will be automatically combined

Views are very easy to establish , Use views correctly , It can greatly simplify complex data processing

Views are updatable , Updating a view will update its base table . If you add or delete rows to the view , In fact, it is to add and delete rows to the base table

Not all views are updatable , Basically , If MySQL The updated base data cannot be determined correctly , Update is not allowed . That is, when the view definition has the following operations, the view cannot be updated

  • grouping
  • coupling
  • Subquery
  • and
  • Aggregation function
  • DISTINCT
  • Calculate columns everywhere

Views are mainly used for data retrieval , Not for updating

PART23 Using stored procedures

The stored procedure is simple , It is one or more items saved for later use MySQL Collection of statements . It can be treated as a batch file , Although their role is not limited to batch processing

Why use stored procedures

  • By encapsulating the processing in an easy-to-use unit , Simplify complex operations
  • It is not required to repeatedly establish a series of treatments , Data integrity guaranteed
  • Simplify management of change

Limiting access to basic data through stored procedures reduces the chance of data corruption ( Data corruption caused by unconscious or other reasons )

Stored procedures have 3 There are two main benefits , Simple 、 Security 、 Efficient .

generally speaking , The writing of stored procedures is better than basic SQL Complex sentences , You may not have the permissions of common stored procedures

Create stored procedure

mysql> delimiter //
mysql> create procedure productpricing()
    -> begin
    -> select avg(prod_price) as priceaverage
    -> from products;
    -> end //
Query OK, 0 rows affected (0.02 sec)

mysql> delimiter ;
mysql> call productpricing();

If the stored procedure accepts parameters , Will be in () To list out , Continue stored procedure does not accept parameters , But the heel () Still need .begin and end Statement is used to define the body of a stored procedure

delimter // Tell the command line utility to use // As a new statement end separator

Delete stored procedure

drop procedure productpricing;

Using parameter

Stored procedures do not display results , Instead, it returns the result to the specified variable .

Variable , A specific location in memory , Used to temporarily store data



create procedure productpricing(
	out p1 decimal(8,2),
    out ph decimal(8,2),
    out pa decimal(8,2)
)
begin 
	select min(prod_price)
    into p1
    from products;
    
	select max(prod_price)
    into ph
    from products;
    
	select avg(prod_price)
    into pa
    from products;
    
end;

  • out Keywords indicate The corresponding parameter is used to get a value from the stored procedure ( Back to the caller )
  • in Pass to stored procedure
  • out Out of stored procedure
  • inout Pass in and out of stored procedures

The code for the stored procedure is located in begin and end In the sentence

The data types allowed by the parameters in the stored procedure are the same as those used in the table , Recordset is not an allowed type

call productpricing(
	@pricelow,
    @pricehigh,
    @priceaverage
    );
    
select @priceaverage;
select 	@pricelow,@pricehigh,@priceaverage;
create procedure ordertotal(
	in onnumber int,
    out ototal decimal(8,2)
)
begin 
	select sum(item_price*quantity)
    from orderitems
    where order_num=onnumber
    into ototal;
end;

call ordertotal(20005,@total);
select @total;
create procedure ordertotal(
	in onnumber int,
    in taxtable boolean,
    out ototal decimal(8,2)
)
comment 'Obtain order total, optionally adding tax'
begin 
	declare total decimal(8,2);
    declare taxrate int default 6;


	select sum(item_price*quantity)
    from orderitems
    where order_num=onnumber
    into total;
    
    if taxable then
		select total+(total/100*taxrate ) into total;
	end if;
    select total into ototal;
end;

call ordertotal(20005,0,@total);
select @total;

call ordertotal(20005,1,@total);
select @total;

Use show create procedure sentence To create a stored procedure create sentence

show create procedure ordertotal

Use show procedure statuas Access includes when , A list of stored procedures with details such as who created them

PART2 Use cursors

The reason for using cursors : Need to move forward or backward one or more lines in the retrieved lines

The cursor : One is stored in MySQL Database query on server , It is not a SELECT sentence , But the result set retrieved by the statement

After storing the cursor , The application can scroll or browse the data as needed

Cursors are mainly used for interactive applications , The user needs to scroll the data on the screen , And browse or change the data ,MySQL Cursors can only have stored procedures ( And the function )

Use cursors

  • Before the cursor can be used , You must declare ( Definition ) it
  • Once declared , The cursor must be open for use
  • For data filled cursors , Remove as needed ( retrieval ) All walks of life
  • When ending cursor usage , Cursor must be closed

After declaring the cursor , The cursor can be opened and closed frequently as needed . After the cursor opens , Fetch operations can be performed frequently as needed

Create cursors

DECLARE Statement create cursor , And define the corresponding SELECT sentence , Bring... As needed WHERE And other clauses

Open cursor

For cursor OPEN CURSOR Statement to open , Processing OPEN Statement , Store retrieved data for browsing and scrolling

Close cursor

CLOSE: Release all internal storage and resources used by the cursor , So every cursor should be closed when it is not needed .

After a cursor closes , If it's not reopened , You can't use it . however , The cursor that has been described does not need to be declared again , Use OPEN Statement can open it .

If you don't explicitly close the cursor ,MySQL Will arrive at END Statement automatically closes it

create procedure processorders()
begin
	declare ordernumbers cursor for select order_num from orders;
    open ordernumbers;
    close ordernumbers;
end

Use cursor data

After a cursor is opened , have access to fetch Statement to access each line of it separately .fetch Specify what data to retrieve ( Required columns ), Where is the retrieved data stored .

It also moves the inner row pointer in the cursor forward , Make the next fetch Statement to retrieve the next line ( Do not read the same line repeatedly )

Retrieve a single row from the cursor ( first line )

create procedure processorders()
begin
	declare o int;
	declare ordernumbers cursor for select order_num from orders;
    open ordernumbers;
    fetch ordernumbers into o;
    close ordernumbers;
end
create procedure processorders()
begin
	declare done boolean default 0;
	declare o int;
	declare ordernumbers cursor for select order_num from orders;
    declare continue handler for sqstate '02000' set done =1;
    open ordernumbers;
    repeat
		fetch ordernumbers into o;
	until done end repeat;
    close ordernumbers;
end
create procedure processorders()
begin
	declare done boolean default 0;
	declare o int;
    declare t decimal (8,2);
    
	declare ordernumbers cursor for select order_num from orders;
    declare continue handler for sqlstate '02000' set done =1;
    
    create table if not exists ordertotals(order_num int, total decimal(8,2));
    
    open ordernumbers;
    repeat
		fetch ordernumbers into o;
        call ordertotal(o,1,t);
        
        insert into ordertotals(order_num,total)
        values(o,t);
	until done end repeat;
    close ordernumbers;
end

PART25 Use triggers

trigger : Need to automatically process when a table changes . trigger , yes MySQL Automatically executed in response to any of the following statements MySQL sentence ( Or located BEGIN and END A set of statements between statements )

  • delete
  • insert
  • update

Create trigger

Create trigger , The following information is required

  • Unique trigger name
  • Trigger associated table
  • Trigger should respond to the activity
  • When the trigger executes

The trigger name must be unique in each table , But it's not unique in every database , This indicates that two tables in the same database can have triggers with the same name

Only tables support triggers , View does not support

create trigger newproduct after insert on products
for each row select 'Product add';

Triggers are defined for each table at each time , Each table allows only one trigger at a time . Each table supports up to 6 Trigger ( Every one of them INSERT、UPDATE and DELETE Before and after ). A single trigger cannot be associated with multiple events or tables

Delete trigger

drop trigger newproduct;

Triggers cannot be updated or overridden . To modify a trigger , You must delete it first , And then recreate

Use triggers

INSERT trigger

INSERT Trigger in INSERT Statement before or after execution

  • stay INSERT Trigger code inside , You can use a reference called NEW The virtual table of , Access the inserted row
  • stay before insert Trigger ,new Values in can also be updated
  • about INSERT_increment Column ,new stay insert Include... Before execution 0, stay insert Include new auto generated values after execution
create trigger neworder after insert on orders
for each row select new.order_num;

insert into orders(order_date,cust_id)
values(now(),1001);

before For data validation and purification ( The purpose is to ensure that the data inserted into the table is really the required data )

DELETE trigger

  • delete Trigger code , You can quote a name as OLD The virtual table of , Access to deleted lines
  • OLD All values in are read-only , Can't update
create trigger deleteorder before delete on orders
for each row
begin
	insert into archive_orders(order_num,order_date,cust_id)
    values(old.order_num,old.order_date,old.cust_id);
end;

update trigger

  • update Trigger , You can quote a name as OLD Before virtual table access update The value before the statement , Quote a name as new Virtual table access new updated values
  • stay before update Trigger ,new Values in may also be updated , Allow changes to be used for update Value in statement
  • old The values in are all read-only , Can't update
create trigger updatevendor before update on vendors
for each row set new.vend_state=upper(new.vend_state);

PART26 Manage transactions

Business management : It can be used to maintain the integrity of the database , It is guaranteed in batches MySQL Operation or full execution , Or not at all

Business management , It's a mechanism , Used to manage what must be executed in batches MySQL operation , To ensure that the database does not contain incomplete operation results . Using transaction processing , It can ensure that a group of operations will not stop halfway , It may be implemented as a whole , Or the star of total death . If no dislocation occurs , The whole set of statements is submitted to ( writes ) Database table . If an error occurs , Then back off , To restore the database to a known and secure state

  • Business : A group of SQL sentence
  • Back off , To revoke a designation SQL Statement procedure
  • Submit , To be stored for SQL Statement result written to database table
  • Reservation point , Temporary placeholder set in transaction , You can post it back ( Unlike backing back the entire transaction )

Control transactions

The key to managing transactions is to SQL Statement groups are broken down into logical blocks , And specify when the data should be rolled back , When not to go back

start transaction

Identify the beginning of the transaction

Use ROLLBACK Used to go back ( revoke )MySQL sentence

select * from ordertotals;
start transaction;
delete from ordertotals;
select *from ordertotals;
rollback;
select *from ordertotals;

ROLLBACK Can only be used within one transaction

Transactions are used to manage INSERT、UPDATE and DELETE sentence , Can't back SELECT sentence , Can't back CREATE or DROP operation

Use COMMIT

MySQL Statements are executed and written for database tables , That is, implicit submission , That is to submit ( Write or save ) The operation is automatic

however , In transaction processing , Submission does not imply , To make a clear submission , Use commit sentence

select transaction;
delete from orderitems where order_num=20010;
delete from orders where order_num=20010;
commit;

When commit or rollback After statement execution , The transaction will close automatically

Use hold points

ordinary ROLLBACK and COMMIT Statement can write or undo the entire transaction , however , This can only be done for simple transactions , More complex transactions may require partial commit or fallback

In order to support fallback of partial transactions , You must be able to place a placeholder in the right place in the transaction block . such , If you need to go back , You can go back to a placeholder

These placeholders are called retention points , To create a placeholder , But the use of SAVEPOINT sentence

SAVEPOINT delete1;

Each reservation takes a unique name that identifies it , So that when you go back ,MySQL Know where to go back .

rollback to delete1

The more reserves, the better

Release the hold : The reservation is automatically released after the transaction is completed , Also available release savepoin Clearly point out the release retention point

Change the default commit behavior

default MySQL Yes automatically commit all changes . Can be specified MySQL Don't commit changes automatically

set autocommit =0 ;

Set up autocommit by 0( false ) instructions MySQL Don't commit changes automatically

PART27 Globalization and localization

Terms commonly used in data sets :

  • Character set : A collection of letters and symbols
  • code , The internal representation of a character set member
  • proofreading , An instruction that specifies how characters are compared

show character set

Displays the default and all available character sets

show collattion

Show all available proofs , And the character set they use , The character set has more than one proofreading

System management will define a default character set and proofreading . Besides , You can also create a database , Specify the default character set and proofreading

show variables like 'character%';
show variables like 'collation%';

To assign datasets and proofs to tables , You can use the create table sentence

create table mytable
(
	columnn1 int,
    columnn2   varchar(10)
)
default character set hebrew
collate hebrew_general_ci;
  • If specified character set and collate both , Then use these values
  • If only character set, Then use this character set and its default proofing
  • If you don't specify character set, It doesn't specify collate, The database default is used

MySQL It is also allowed to set

create table mytable
(
	columnn1 int,
    columnn2   varchar(10),
    columnn3 varchar(10) character set latin1 collate latin1_general_ci
)
default character set hebrew
collate hebrew_general_ci;

Sort specific with a proofing order that is different from creating a table select sentence , Can be in select Statement itself

select *from customers
order by lastname,firstname collate latin1_general_ci

PART28 security management

MySQL The security foundation of the server is : Users should have proper access to the data they need , No more, no less

Access control , You need to provide users with appropriate access , Managing access control requires creating and managing user accounts

Manage users

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select user from user;

Create user account

create user ben identified by '[email protected]$$w0rd';

Rename user account

rename user ben to bforta;

Delete user account

drop user bforta;

Set access rights

 Change password show grants for bforta

grant Statements must have the following information

  • Permission granted
  • A database or table to which access is granted
  • user name
grant select on crashcourse.* to bforta

Revoke specific permissions

revoke select on crashcourse.* from bforta

Granting and revoking specific access rights can be controlled at several levels

  • Entire server , Use grant all and revoke all
  • Entire database , Use on database .*
  • Specific tables , Use on database.table
  • Specific columns
  • Specific stored procedures

Change password

set password for bforta =password('n3w [email protected]$$w0rd');

原网站

版权声明
本文为[Yingtai night snow]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061135127729.html