当前位置:网站首页>MySQL advanced statement 2

MySQL advanced statement 2

2022-06-23 15:01:00 [email protected]

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