MySQL high-level statements


Before proceeding with advanced SQL statements, create two tables

use edg;
create table localtion (Region char(20),Store_Name char(20));
insert into localtion values('East','Boston');
insert into localtion values('East','New York');
insert into localtion values('West','Los Angeles');
insert into localtion values('West','Houston');

Insert picture description here

create table Store_Info (Store_Name char(20),Sales int(10),Date char(10));
insert into Store_Info values('Los Angeles','1500','2020-12-05');
insert into Store_Info values('Houston','250','2020-12-07');
insert into Store_Info values('Los Angeles','300','2020-12-08');
insert into Store_Info values('Boston','700','2020-12-08');

Insert picture description here

1. Introduction to MySQL Advanced Statement

1. SELECT: Display all data in one or several fields in the table

语法:SELECT "栏位" FROM "表名";
SELECT Store_Name FROM Store_Info;

Insert picture description here
2. DISTINCT: Do not display duplicate data

语法:SELECT DISTINCT "栏位" FROM "表名";
SELECT DISTINCT Store_Name FROM Store_Info;

Insert picture description here
3. WHERE: Conditional query

语法:SELECT "栏位" FROM "表名" WHERE "条件";
SELECT Store_Name FROM Store_Info WHERE Sales > 1000;

Insert picture description here
4. AND OR: and or

语法:SELECT "栏位" FROM "表名" WHERE "条件1" {[AND|OR] "条件2"}+ ;
SELECT Store_Name FROM Store_Info WHERE Sales > 1000 OR (Sales < 500 AND Sales > 200);

Insert picture description here
5. IN: Display the data of the known value

语法:SELECT "栏位" FROM "表名" WHERE "栏位" IN ('值1', '值2', ...);
SELECT * FROM Store_Info WHERE Store_Name IN ('Los Angeles', 'Houston');

Insert picture description here
6. BETWEEN: Display data within two value ranges

语法:SELECT "栏位" FROM "表名" WHERE "栏位" BETWEEN '值1' AND '值2';
SELECT * FROM Store_Info WHERE Sales BETWEEN '250' AND '700';

Insert picture description here
7. Wildcards: usually wildcards are used together with LIKE

% :百分号表示零个、一个或多个字符
_ :下划线表示单个字符

'A_Z':所有以 'A' 起头,另一个任何值的字符,且以 'Z' 为结尾的字符串。例如,'ABZ' 和 'A2Z' 都符合这一个模式,而 'AKKZ' 并不符合 (因为在 A 和 Z 之间有两个字符,而不是一个字符)。
'ABC%': 所有以 'ABC' 起头的字符串。例如,'ABCD' 和 'ABCABC' 都符合这个模式。
'%XYZ': 所有以 'XYZ' 结尾的字符串。例如,'WXYZ' 和 'ZZXYZ' 都符合这个模式。
'%AN%': 所有含有 'AN'这个模式的字符串。例如,'LOS ANGELES' 和 'SAN FRANCISCO' 都符合这个模式。
'_AN%':所有第二个字母为 'A' 和第三个字母为 'N' 的字符串。例如,'SAN FRANCISCO' 符合这个模式,而 'LOS ANGELES' 则不符合这个模式。

8. LIKE: Match a pattern to find out the information we want

语法:SELECT "栏位" FROM "表名" WHERE "栏位" LIKE {模式};
SELECT * FROM Store_Info WHERE Store_Name like '%os%';

Insert picture description here
9. ORDER BY: sort by keywords

语法:SELECT "栏位" FROM "表名" [WHERE "条件"] ORDER BY "栏位" [ASC, DESC];
#ASC 是按照升序进行排序的,是默认的排序方式。
#DESC 是按降序方式进行排序。
SELECT Store_Name,Sales,Date FROM Store_Info ORDER BY Sales DESC;

Insert picture description here
10. Function
Mathematical function:
Insert picture description here

SELECT abs(-1), rand(), mod(5,3), power(2,3), round(1.89);
SELECT round(1.8937,3), truncate(1.235,2), ceil(5.2), floor(2.1), least(1.89,3,6.1,2.1);

11. Aggregate functions
Insert picture description here

SELECT avg(Sales) FROM Store_Info;

SELECT count(Store_Name) FROM Store_Info;
SELECT count(DISTINCT Store_Name) FROM Store_Info;

SELECT max(Sales) FROM Store_Info;
SELECT min(Sales) FROM Store_Info;

SELECT sum(Sales) FROM Store_Info;

12. String functions
Insert picture description here

SELECT concat(Region, Store_Name) FROM localtion WHERE Store_Name = 'Boston';
#如sql_mode开启开启了PIPES_AS_CONCAT,"||"视为字符串的连接操作符而非或运算符,和字符串的拼接函数Concat相类似,这和Oracle数据库使用方法一样的
SELECT Region || ' ' || Store_Name FROM localtion WHERE Store_Name = 'Boston';

SELECT substr(Store_Name,3) FROM localtion WHERE Store_Name = 'Los Angeles';
SELECT substr(Store_Name,2,4) FROM localtion WHERE Store_Name = 'New York';

SELECT TRIM ([ [位置] [要移除的字符串] FROM ] 字符串);
#[位置]:的值可以为 LEADING (起头), TRAILING (结尾), BOTH (起头及结尾)。 
#[要移除的字符串]:从字串的起头、结尾,或起头及结尾移除的字符串。缺省时为空格。

SELECT TRIM(LEADING 'Ne' FROM 'New York');

SELECT Region,length(Store_Name) FROM localtion;

SELECT REPLACE(Region,'ast','astern')FROM localtion;

13. GROUP BY: aggregate and group the query results of the column after GROUP BY. GROUP BY is usually used in combination with aggregate functions.
There is a principle of GROUP BY, that is, in all columns after SELECT, columns that do not use aggregate functions must appear After GROUP BY.

语法:SELECT "栏位1", SUM("栏位2") FROM "表名" GROUP BY "栏位1";
SELECT Store_Name, SUM(Sales) FROM Store_Info GROUP BY Store_Name ORDER BY sales desc;

Insert picture description here
14. HAVING: Used to filter the record table returned by the GROUP BY statement. The
HAVING statement is usually used in conjunction with the GROUP BY statement to make up for the insufficiency of the WHERE keyword cannot be used in conjunction with aggregate functions. If only the function column is selected, the GROUP BY clause is not required.

语法:SELECT "栏位1", SUM("栏位2") FROM "表格名" GROUP BY "栏位1" HAVING (函数条件);
SELECT Store_Name, SUM(Sales) FROM Store_Info GROUP BY Store_Name HAVING SUM(Sales) > 1500;

Insert picture description here
15. Alias: field alias table alias

语法:SELECT "表格別名"."栏位1" [AS] "栏位別名" FROM "表格名" [AS] "表格別名";
SELECT A.Store_Name Store, SUM(A.Sales) "Total Sales" FROM Store_Info A GROUP BY A.Store_Name;

Insert picture description here
16. Subquery: join table, insert another SQL statement in sub WHERE clause or HAVING clause

语法:SELECT "栏位1" FROM "表格1" WHERE "栏位2" [比较运算符]			#外查询
(SELECT "栏位1" FROM "表格2" WHERE "条件");							#内查询
#可以是符号的运算符,例如:=、>、<、>=、<= ;也可以是文字的运算符,例如 LIKE、IN、BETWEEN
SELECT SUM(Sales) FROM Store_Info WHERE Store_Name IN
(SELECT Store_Name FROM localtion WHERE Region = 'West');

SELECT SUM(Sales) FROM Store_Info WHERE Store_Name IN ('Los Angeles','Houston');

SELECT SUM(A.Sales) FROM Store_Info A WHERE A.Store_Name IN
(SELECT Store_Name FROM localtion B WHERE B.Store_Name = A.Store_Name);

Insert picture description here
Insert picture description here
Insert picture description here
17. EXISTS: Used to test whether the inner query produces any results, similar to whether the Boolean value is true.
If so, the system will execute the SQL statement in the outer query. If not, then the entire SQL statement will not produce any results.

语法:SELECT "栏位1" FROM "表格1" WHERE EXISTS (SELECT * FROM "表格2" WHERE "条件");
SELECT SUM(Sales) FROM Store_Info WHERE EXISTS (SELECT * FROM localtion WHERE Region = 'West');

Insert picture description here

Two, connection query

The location table remains unchanged, modify the Store_Info table

UPDATE Store_Info SET store_name='Washington' WHERE sales=300;

1, inner join (equal value connection): only return rows with equal join fields in the two tables

SELECT * FROM localtion A INNER JOIN Store_Info B on A.Store_Name = B.Store_Name;

Insert picture description here
2, left join (left join): return including all records in the left table and the join field in the right table is equal to the record

SELECT * FROM localtion A left JOIN Store_Info B on A.Store_Name = B.Store_Name;

Insert picture description here3, right join (right join): return including all records in the right table and the join field in the left table is equal to the record

SELECT * FROM localtion A RIGHT JOIN Store_Info B on A.Store_Name = B.Store_Name;

Insert picture description here

Three, CREATE VIEW view

Note: The difference between the view and the table is that the table has the actual stored data, and the view is a structure built on the table, and it does not actually store the data.
The temporary table automatically disappears after the user exits or the connection with the database is disconnected, and the view does not disappear.
The view does not contain data, only its definition is stored. Its purpose is generally to simplify complex queries. For example, if you want to connect and query several tables, and also perform statistical sorting and other operations, it will be very troublesome to write SQL statements. Use a view to connect several tables, and then perform a query operation on this view, just like a table It's very convenient to query the same.

语法:CREATE VIEW "视图表名" AS "SELECT 语句";
CREATE VIEW V_REGION_SALES AS SELECT A.Region REGION,SUM(B.Sales) SALES FROM localtion A 
INNER JOIN Store_Info B ON A.Store_Name = B.Store_Name GROUP BY REGION;

SELECT * FROM V_REGION_SALES;
DROP VIEW V_REGION_SALES;

Insert picture description here

Fourth, MySQL's union, intersection value, non-intersection value, case

1. Union, which combines the results of two SQL statements. The fields generated by the two SQL statements need to be of the same data type
(1) UNION:

UNION :生成结果的资料值将没有重复,且按照字段的顺序进行排序
语法:[SELECT 语句 1] UNION [SELECT 语句 2];

SELECT Store_Name FROM localtion UNION SELECT Store_Name FROM Store_Info;

(2)UNION ALL

UNION ALL :将生成结果的资料值都列出来,无论有无重复
语法:[SELECT 语句 1] UNION ALL [SELECT 语句 2];

SELECT Store_Name FROM localtion UNION ALL SELECT Store_Name FROM Store_Info;

2. Intersection value: take the intersection of the results of the two SQL statements

SELECT A.Store_Name FROM localtion A INNER JOIN Store_Info B ON A.Store_Name = B.Store_Name;

SELECT A.Store_Name FROM localtion A INNER JOIN Store_Info B USING(Store_Name);
两表没用重复的行,并且确实有交集的时候用
SELECT A.Store_Name FROM 
(SELECT Store_Name FROM localtion UNION ALL SELECT Store_Name FROM Store_Info) A 
GROUP BY A.Store_Name HAVING COUNT(*) > 1;
取两个SQL语句结果的交集,且没有重复
SELECT A.Store_Name FROM (SELECT B.Store_Name FROM localtion B INNER JOIN Store_Info C ON B.Store_Name = C.Store_Name) A 
GROUP BY A.Store_Name;

SELECT DISTINCT A.Store_Name FROM localtion A INNER JOIN Store_Info B USING(Store_Name);

SELECT DISTINCT Store_Name FROM localtion WHERE (Store_Name) IN (SELECT Store_Name FROM Store_Info);

SELECT DISTINCT A.Store_Name FROM localtion A 
LEFT JOIN Store_Info B USING(Store_Name) WHERE B.Store_Name IS NOT NULL;

3. No intersection value: display the result of the first SQL statement, and there is no intersection result with the second SQL statement, and there is no duplication

SELECT DISTINCT Store_Name FROM localtion WHERE (Store_Name) NOT IN (SELECT Store_Name FROM Store_Info);

SELECT DISTINCT A.Store_Name FROM localtion A 
LEFT JOIN Store_Info B USING(Store_Name) WHERE B.Store_Name IS NULL;

4. CASE: SQL is used as a keyword for logic such as IF-THEN-ELSE.
Syntax:

SELECT CASE ("栏位名")
  WHEN "条件1" THEN "结果1"
  WHEN "条件2" THEN "结果2"
  ...
  [ELSE "结果N"]
  END
FROM "表名";

# "条件" 可以是一个数值或是公式。 ELSE 子句则并不是必须的。

Five, sort

Preparation before sorting:

CREATE TABLE Total_Sales (Name char(10),Sales int(5));
INSERT INTO Total_Sales VALUES ('zhangsan',10);
INSERT INTO Total_Sales VALUES ('lisi',15);
INSERT INTO Total_Sales VALUES ('wangwu',20);
INSERT INTO Total_Sales VALUES ('zhaoliu',40);
INSERT INTO Total_Sales VALUES ('sunqi',50);
INSERT INTO Total_Sales VALUES ('zhouba',20);
INSERT INTO Total_Sales VALUES ('wujiu',30);

1. Calculate the ranking table self-join (Self Join), and then list the results in sequence, and calculate how many rows are before each row (including the row itself)

SELECT A1.Name, A1.Sales, COUNT(A2.Sales) Rank FROM Total_Sales A1, Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;

Insert picture description here
Count that the value of the Sales field is smaller than its own value and the number of the Sales field and the Name field are the same
2, the median

SELECT Sales Middle FROM (SELECT A1.Name,A1.Sales,COUNT(A2.Sales) Rank FROM Total_Sales A1,Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name <= A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC) A3 
WHERE A3.Rank = (SELECT (COUNT(*)+1) DIV 2 FROM Total_Sales);

Insert picture description here
Each derived table must have its own alias
3. Calculate the cumulative total table self-join (Self Join), and then sequence the results to calculate the total before each row (including the row itself)

SELECT A1.Name, A1.Sales, SUM(A2.Sales) Sum_Total FROM Total_Sales A1, Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;

Insert picture description here
4. Total percentage

SELECT A1.Name, A1.Sales, A1.Sales/(SELECT SUM(Sales) FROM Total_Sales) Per_Total 
FROM Total_Sales A1, Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;

#SELECT SUM(Sales) FROM Total_Sales 这一段子查询是用来算出总合
#总合算出后,我们就能够将每一行一一除以总合来求出每一行的总合百分比

Insert picture description here
5. Percentage of cumulative total

SELECT A1.Name, A1.Sales, SUM(A2.Sales)/(SELECT SUM(Sales) FROM Total_Sales) Per_Total 
FROM Total_Sales A1, Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales and A1.Name = A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;

Insert picture description here
Divide the cumulative total SUM(a2.Sales) by the total to find the cumulative total percentage of each row

SELECT A1.Name, A1.Sales, TRUNCATE(ROUND(SUM(A2.Sales)/(SELECT SUM(Sales) FROM Total_Sales),4)*100,2) || '%' Per_Total 
FROM Total_Sales A1, Total_Sales A2 
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales and A1.Name = A2.Name) 
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;

Insert picture description here

Six, the difference between null and no value

1.无值的长度为 0,不占用空间的;而 NULL 值的长度是 NULL,是占用空间的。
2.IS NULL 或者 IS NOT NULL,是用来判断字段是不是为 NULL 或者不是 NULL,不能查出是不是无值的。
3.无值的判断使用=''或者<>''来处理。<> 代表不等于。
4.在通过 count()指定字段统计有多少行数时,如果遇到 NULL 值会自动忽略掉,遇到无值会加入到记录中进行计算。
SELECT length(NULL), length(''), length('1');
SELECT * FROM city WHERE name IS NULL;
SELECT * FROM city WHERE name IS NOT NULL;
SELECT * FROM city WHERE name = '';
SELECT * FROM city WHERE name <> '';
SELECT COUNT(*) FROM city;
SELECT COUNT(name) FROM city;

Seven, regular expressions

匹配模式			描述									实例
^ 				匹配文本的开始字符 						‘^bd’ 匹配以 bd 开头的字符串
$ 				匹配文本的结束字符 						‘qn$’ 匹配以 qn 结尾的字符串
. 				匹配任何单个字符							‘s.t’ 匹配任何 s 和 t 之间有一个字符的字符串
* 				匹配零个或多个在它前面的字符 				‘fo*t’ 匹配 t 前面有任意个 o
+ 				匹配前面的字符 1 次或多次					‘hom+’ 匹配以 ho 开头,后面至少一个m 的字符串
字符串 			匹配包含指定的字符串 						‘clo’ 匹配含有 clo 的字符串
p1|p2 			匹配 p1 或 p2 							‘bg|fg’ 匹配 bg 或者 fg
[...] 			匹配字符集合中的任意一个字符 				‘[abc]’ 匹配 a 或者 b 或者 c
[^...] 			匹配不在括号中的任何字符 					‘[^ab]’ 匹配不包含 a 或者 b 的字符串
{n} 			匹配前面的字符串 n 次 					‘g{2}’ 匹配含有 2 个 g 的字符串
{n,m}			匹配前面的字符串至少 n 次,至多m 次		‘f{1,3}’ 匹配 f 最少 1 次,最多 3 次

Syntax format:

语法:SELECT "栏位" FROM "表名" WHERE "栏位" REGEXP {模式};
SELECT * FROM Store_Info WHERE Store_Name REGEXP 'os';
SELECT * FROM Store_Info WHERE Store_Name REGEXP '^[A-G]';
SELECT * FROM Store_Info WHERE Store_Name REGEXP 'Ho|Bo';

8. Storage process

1. A stored procedure is a set of SQL statements to complete a specific function.
2. In the process of using stored procedures, common or complex tasks are written in advance using SQL statements and stored with a specified name. This process is compiled and optimized and stored in the database server. When you need to use the stored procedure, you only need to call it. Stored procedures are faster and more efficient in execution than traditional SQL.
3. Advantages of stored procedures:
(1) After executing once, the generated binary code will reside in the buffer to improve execution efficiency
(2) SQL statements plus a collection of control statements, high flexibility
(3) Stored on the server side , When the client is called, reduce the network load
(4) It can be called repeatedly and can be modified at any time without affecting the client call.
(5) All database operations can be completed, and the information access authority of the database can also be controlled.
4. Create storage process

DELIMITER $$							#将语句的结束符号从分号;临时改为两个$$(可以是自定义)
CREATE PROCEDURE Proc()					#创建存储过程,过程名为Proc,不带参数
-> BEGIN								#过程体以关键字 BEGIN 开始
-> select * from Store_Info;			#过程体语句
-> END $$								#过程体以关键字 END 结束
DELIMITER ;								#将语句的结束符号恢复为分号

5. Call the stored procedure: CALL Proc;
6. View the stored procedure

SHOW CREATE PROCEDURE [数据库.]存储过程名;		#查看某个存储过程的具体信息
SHOW CREATE PROCEDURE Proc;
SHOW PROCEDURE STATUS [LIKE '%Proc%'] \G

7. The parameter
IN of the stored procedure. Input parameter: indicates that the caller passes in a value to the process (the incoming value can be a literal or variable).
OUT output parameter: indicates that the process passes a value to the caller (can return multiple values) (pass The value can only be a variable)
INOUT input and output parameters: it means that the caller passes in a value to the process, and it also means that the process passes a value to the caller (the value can only be a variable)
8. The
method to modify the contents of a stored procedure to delete a stored procedure is By deleting the original stored procedure, and then create a new stored procedure with the same name.

DROP PROCEDURE IF EXISTS Proc;

9, the control statement of the stored procedure

create table t (id int(10));
insert into t values(10);

(1) Conditional statement if-then-else-end if

DELIMITER $$  
CREATE PROCEDURE proc2(IN parameter int)  
-> begin 
-> declare var int;  
-> set var=parameter*2;   
-> if var>=10 then 
-> update t set id=id+1;  
-> else 
-> update t set id=id-1;  
-> end if;  
-> end $$
 
DELIMITER ;

CALL Proc2(6);

(2) Loop statement while ···· end while

DELIMITER $$  
CREATE PROCEDURE proc3()
-> begin 
-> declare var int(10);  
-> set var=0;  
-> while var<6 do  
-> insert into t values(var);  
-> set var=var+1;  
-> end while;  
-> end $$  

DELIMITER ;

CALL Proc3;

Guess you like

Origin blog.csdn.net/tefuiryy/article/details/113663528