当前位置:网站首页>MySQL advanced statement 2
MySQL advanced statement 2
2022-06-23 15:01:00 【[email protected]】
List of articles
1 EXISTS
It is used to test whether the inner query produces any results , Whether Boolean value is true or not
If any , The system will execute the SQL sentence , If it were not so , The whole SQL Statement will not produce any results .
grammar :SELECT " Field 1" FROM " form 1" WHERE EXISTS (SELECT * FROM " form 2" WHERE " Conditions ");
SELECT SUM(Sales) FROM Store_Info WHERE EXISTS (SELECT * FROM location WHERE Region = 'West');
---- Link query ----
location form
+----------+--------------+
| Region | Store_Name |
|----------+--------------|
| East | Boston |
| East | New York |
| West | Los Angeles |
| West | Houston |
+----------+--------------+
UPDATE Store_Info SET store_name='Washington' WHERE sales=300;
Store_Info form
+--------------+---------+------------+
| Store_Name | Sales | Date |
|--------------+---------+------------|
| Los Angeles | 1500 | 2022-06-05 |
| Houston | 250 | 2022-06-07 |
| Washington | 300 | 2022-06-08 |
| Boston | 700 | 2022-06-08 |
+--------------+---------+------------+
2 inner join、left join、right join
inner join( Internal connection ): Only rows with equal join fields in two tables are returned
grammar :SELECT Field FROM surface 1 INNER JOIN surface 2 ON surface 1. Field = surface 2. Field ;
left join( Left connection ): Returns records that include all records in the left table and join fields in the right table
grammar :SELECT Field FROM surface 1 LEFT JOIN surface 2 ON surface 1. Field = surface 2. Field ;
right join( The right connection ): Returns records that include all records in the right table and join fields in the left table
grammar :SELECT Field FROM surface 1 RIGHT JOIN surface 2 ON surface 1. Field = surface 2. Field ;
SELECT * FROM location A RIGHT JOIN Store_Info B on A.Store_Name = B.Store_Name ;
SELECT * FROM location A LEFT JOIN Store_Info B on A.Store_Name = B.Store_Name ;
Inner connection I :
SELECT * FROM location A INNER JOIN Store_Info B on A.Store_Name = B.Store_Name ;
Inner connection II :
SELECT * FROM location A, Store_Info B WHERE A.Store_Name = B.Store_Name;
SELECT A.Region REGION, SUM(B.Sales) SALES FROM location A, Store_Info B
WHERE A.Store_Name = B.Store_Name GROUP BY REGION;
Self connect , Rank :
+----------+-------+
| name | score |
+----------+-------+
| lisi | 100 |
| zhaoliu | 90 |
| wangwu | 80 |
| zhangsan | 70 |
+----------+-------+
Statistics after grouping and summarizing score The value of the field is smaller than its own value score Field and name The same number of fields
SELECT A.name, A.score, count(B.score) rank FROM class A, class B
WHERE A.score < B.score OR (A.score = B.score AND A.Name = B.Name)
GROUP BY A.name, A.score ORDER BY rank;
3 CREATE VIEW View
View : Can be treated as a virtual table or stored query .
The difference between a view and a table is , There are actually stored data in the table , And a view is a structure built on a table , It doesn't actually store data itself .
The temporary table disappears automatically after the user exits or disconnects from the database , The view does not .
Views don't contain data , Just store its definition , Its purpose is to simplify complex queries . For example, you need to connect and query several tables , But also to carry out statistical sorting and other operations , Write SQL Statements can be cumbersome , Connect several tables with a view , Then query the view , Just like querying a table , Very convenient .
grammar :CREATE VIEW " View table name " AS "SELECT sentence ";
CREATE VIEW V_REGION_SALES AS SELECT A.Region REGION,SUM(B.Sales) SALES FROM location 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;
4 UNION combine
Put two SQL The results of the statement are combined , Two SQL The fields generated by the statement need to be the same data type
UNION: The data value of the generated result will No repetition , And in the order of the fields Sort .
grammar :[SELECT sentence 1] UNION [SELECT sentence 2];
UNION ALL: List the data values of the generated results , With or without repetition
grammar :[SELECT sentence 1] UNION ALL [SELECT sentence 2];
SELECT Store_Name FROM location UNION SELECT Store_Name FROM Store_Info;
SELECT Store_Name FROM location UNION ALL SELECT Store_Name FROM Store_Info;
4.1 Intersection value
Take two. SQL The intersection of statement results
SELECT A.Store_Name FROM location A INNER JOIN Store_Info B ON A.Store_Name = B.Store_Name;
SELECT A.Store_Name FROM location A INNER JOIN Store_Info B USING(Store_Name);
# Take two. SQL The intersection of statement results , And there's no repetition
SELECT DISTINCT A.Store_Name FROM location A INNER JOIN Store_Info B USING(Store_Name);
SELECT DISTINCT Store_Name FROM location WHERE (Store_Name) IN (SELECT Store_Name FROM Store_Info);
SELECT DISTINCT A.Store_Name FROM location A LEFT JOIN Store_Info B USING(Store_Name) WHERE B.Store_Name IS NOT NULL;
SELECT A.Store_Name FROM (SELECT B.Store_Name FROM location B INNER JOIN Store_Info C ON B.Store_Name = C.Store_Name) A
GROUP BY A.Store_Name;
SELECT A.Store_Name FROM
(SELECT DISTINCT Store_Name FROM location UNION ALL SELECT DISTINCT Store_Name FROM Store_Info) A
GROUP BY A.Store_Name HAVING COUNT(*) > 1;
4.2 No intersection value
Show the first SQL Result of statement , And with the second SQL Statement has no result of intersection , And there's no repetition
SELECT DISTINCT Store_Name FROM location WHERE (Store_Name) NOT IN (SELECT Store_Name FROM Store_Info);
SELECT DISTINCT A.Store_Name FROM location A LEFT JOIN Store_Info B USING(Store_Name) WHERE B.Store_Name IS NULL;
SELECT A.Store_Name FROM
(SELECT DISTINCT Store_Name FROM location UNION ALL SELECT DISTINCT Store_Name FROM Store_Info) A
GROUP BY A.Store_Name HAVING COUNT(*) = 1;
5 CASE
yes SQL Used as a IF-THEN-ELSE And so on
grammar :
SELECT CASE (" Field name ")
WHEN " Conditions 1" THEN " result 1"
WHEN " Conditions 2" THEN " result 2"
...
[ELSE " result N"]
END
FROM " Table name ";
# " Conditions " It can be a number or a formula . ELSE Clause is not necessary .
SELECT Store_Name, CASE Store_Name
WHEN 'Los Angeles' THEN Sales * 2
WHEN 'Boston' THEN 2000
ELSE Sales
END
"New Sales",Date
FROM Store_Info;
#"New Sales" Is used for CASE The field name of that field .
6 Null value (null) And no value (’’) The difference between
1. The length of no value is 0, Not taking up space ; and NULL The length of the value is NULL, It takes up space .
2.IS NULL perhaps IS NOT NULL, It is used to judge whether the field is NULL Or not NULL, Can't find out if it's worthless .
3. The judgment without value uses ='‘ perhaps <>’' To deal with it .<> The representative is not equal to .
4. Through count() When specifying the number of rows in the field statistics , If you encounter NULL The value is automatically ignored , If there is no value, it will be added to the record for calculation .
City form
+----------+
| name |
|----------|
| beijing |
| nanjing |
| shanghai |
| <null> |
| <null> |
| shanghai |
| |
+----------+
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;
7 Regular expressions ( And Shell Part of the same )
Matching mode describe example
^ Match the start character of the text ‘^bd’ Match with bd Starting string
$ Match the end character of the text ‘qn$’ Match with qn a null-terminated string
. Match any single character ‘s.t’ Match any s and t A string with one character between
* Match zero or more characters before it ‘fo*t’ matching t There is any one in front o
+ Match preceding characters 1 Times or times ‘hom+’ Match with ho start , At least one back m String
character string Match contains the specified string ‘clo’ The match contains clo String
p1|p2 matching p1 or p2 ‘bg|fg’ matching bg perhaps fg
[...] Match any character in the character set ‘[abc]’ matching a perhaps b perhaps c
[^...] Match any characters that are not in brackets ‘[^ab]’ Match does not contain a perhaps b String
{
n} Match the previous string n Time ‘g{
2}’ The match contains 2 individual g String
{
n,m} Match the previous string at least n Time , at most m Time ‘f{
1,3}’ matching f least 1 Time , most 3 Time
grammar :SELECT " Field " FROM " Table name " WHERE " Field " REGEXP {
Pattern };
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 stored procedure ( And Shell The function is almost , Code reuse )
A stored procedure is a set of functions to accomplish SQL Statement set
In the process of using stored procedures, common or complex work is used in advance SQL The statement is written and stored with a specified name , This process is compiled and optimized and stored in the database server , When you need to use this stored procedure , Just call it , Stored procedures perform better than traditional SQL Faster , More efficient execution .
Advantages of stored procedures
1、 After one execution , The generated binary code will reside in the buffer , Improve execution efficiency
2、SQL Statement plus a collection of control statements , High flexibility
3、 Store on the server side , When called by the client , Reduce network load
4、 Can be called repeatedly , Can be modified at any time , Does not affect client calls
5、 Can complete all database operations , You can also control the information access rights of the database
8.1 Create stored procedure
DELIMITER $$ # Change the closing sign of the statement from a semicolon ; Temporarily changed to two $$( It can be custom )
CREATE PROCEDURE Proc() # Create stored procedure , The process name is Proc, With no arguments
-> BEGIN # The process body takes the keyword BEGIN Start
-> select * from Store_Info; # Process style sentences
-> END $$ # The process body takes the keyword END end
DELIMITER ; # Returns the ending symbol of the statement to a semicolon
8.2 Calling stored procedure
CALL Proc;
8.3 View stored procedures
SHOW CREATE PROCEDURE [ database .] Stored procedure name ; # View the specific information of a stored procedure
SHOW CREATE PROCEDURE Proc;
SHOW PROCEDURE STATUS [LIKE '%Proc%'] \G
8.4 Parameters of stored procedure
IN Input parameters : Indicates that the caller passes a value... To the procedure ( The incoming value can be literal or variable )
OUT Output parameters : Indicates that the procedure passes out a value to the caller ( Multiple values can be returned )( Outgoing values can only be variables )
INOUT Input/output parameter : It means that the caller passes in a value to the procedure , It also indicates that the procedure passes out a value to the caller ( Values can only be variables )
DELIMITER $$
CREATE PROCEDURE Proc1(IN inname CHAR(16))
-> BEGIN
-> SELECT * FROM Store_Info WHERE Store_Name = inname;
-> END $$
DELIMITER ;
CALL Proc1('Boston');
8.5 Delete stored procedure
The method to modify the contents of stored procedures is to delete the original stored procedures , Then create a new stored procedure with the same name .
DROP PROCEDURE IF EXISTS Proc; # Delete... Only if it exists , Don't add IF EXISTS when , If the specified procedure does not exist , Then there is an error
8.6 Control statement of stored procedure
create table t (id int(10));
insert into t values(10);
(1) Conditional statements if-then-else ···· end if
DELIMITER $$
CREATE PROCEDURE proc2(IN pro int)
-> begin
-> declare var int;
-> set var=pro*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;
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231403130674.html
边栏推荐
- [datahub] LinkedIn datahub learning notes
- Effect evaluation of regression model under credit product quota pricing scenario
- 2021-05-08
- Networknt:: JSON schema validator source code appreciation
- Ie mode of selenium edge
- WPF (c) open source control library: newbeecoder Nbexpander control of UI
- 建議自查!MySQL驅動Bug引發的事務不回滾問題,也許你正面臨該風險!
- Quick view of wechat applet development process
- WPF (c) new open source control library: newbeecoder UI waiting animation
- In this year's English college entrance examination, CMU delivered 134 high scores with reconstruction pre training, significantly surpassing gpt3
猜你喜欢

2021-06-03

分布式数据库使用逻辑卷管理存储之扩容

Auto - vérification recommandée! Les bogues MySQL ne font pas reculer les transactions, peut - être êtes - vous à risque!

An idea plug-in for automatically generating unit tests

k8s--部署单机版MySQL,并持久化

useState vs useRef 和 useReducer:相同点、不同点和用例

去 OPPO 面试, 被问麻了。。。

Tencent ECS failed to send email

After nine years at the helm, the founding CEO of Allen Institute retired with honor! He predicted that Chinese AI would lead the world

Millions of bonuses are waiting for you to get. The first China Yuan universe innovation and application competition is in hot Recruitment!
随机推荐
【二级等保】过二级等保用哪个堡垒机品牌好?
Mysql双主配置的详细步骤
谷歌&HuggingFace| 零样本能力最强的语言模型结构
[datahub] LinkedIn datahub learning notes
分布式数据库使用逻辑卷管理存储之扩容
How does activity implement lifecycleowner?
Selenium Edge的IE模式
AXI_Round_Robin_Arbiter 设计 - AW、W通道部分
2021-06-07
The first public available pytorch version alphafold2 is reproduced, and Columbia University is open source openfold, with more than 1000 stars
如何使用笔记软件 FlowUs、Notion 进行间隔重复?基于公式模版
如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
Effect evaluation of regression model under credit product quota pricing scenario
Execute the sc.exe QC command to query some services. The data area passed to the system call is too small
Test article
2021-04-15
raspberry pi安装 wiringpi
k8s--部署单机版MySQL,并持久化
2021-06-07
Use of pyqt5 tool box