MySQL Advanced SQL Statements (2)

1. MySQL advanced SQL statement

1.1 Connection query

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

inner join(内连接):只返回两个表中联结字段相等的行
left join(左连接):返回包括左表中的所有记录和右表中联结字段相等的记录 
right join(右连接):返回包括右表中的所有记录和左表中联结字段相等的记录

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 ;

内连接一:
SELECT * FROM location A INNER JOIN Store_Info B on A.Store_Name = B.Store_Name ;

内连接二:
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;

insert image description here
insert image description here
insert image description here

1.2 CREATE VIEW view can be regarded as a virtual table or stored query

  • The difference between a view and a table is that the table actually stores data records, while the view is a structure built on the table, and it does not actually store data records.
  • Temporary tables disappear automatically after the user logs out or the connection to the database is disconnected, but the view does not disappear.
  • A view does not contain data, only its definition is stored, and its use generally simplifies complex queries. For example, if you want to perform join queries on several tables, and also perform statistical sorting operations, it will be very troublesome to write SQL statements. Using a view to join several tables, and then performing query operations on this view is the same as performing operations on one table. Queries are the same, very convenient.
语法:CREATE VIEW "视图表名" AS "SELECT 语句";
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;

insert image description here
insert image description here
insert image description here
insert image description here

1.3 UNION union

  • Merge the results of two SQL statements, and the fields generated by the two SQL statements must be of the same data record type
UNION :生成结果的数据记录值将没有重复,且按照字段的顺序进行排序
语法:[SELECT 语句 1] UNION [SELECT 语句 2];

UNION ALL :将生成结果的数据记录值都列出来,无论有无重复
语法:[SELECT 语句 1] UNION ALL [SELECT 语句 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;
---- 交集值 ----取两个SQL语句结果的交集
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);

#取两个SQL语句结果的交集,且没有重复
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;

---- 无交集值 ----显示第一个SQL语句的结果,且与第二个SQL语句没有交集的结果,且没有重复
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;

insert image description here
insert image description here
insert image description here
insert image description here
insert image description hereinsert image description here
insert image description here

1.4 CASE

#是 SQL 用来做为 IF-THEN-ELSE 之类逻辑的关键字
语法:
SELECT CASE ("字段名")
  WHEN "条件1" THEN "结果1"
  WHEN "条件2" THEN "结果2"
  ...
  [ELSE "结果N"]
  END
FROM "表名";

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

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" 是用于 CASE 那个字段的字段名。

insert image description here

1.5 Difference between empty value (NULL) and no value ('')

1. The length of no value is 0, which does not occupy space; while the length of NULL value is NULL, which occupies space.
2. IS NULL or IS NOT NULL is used to judge whether the field is NULL or not NULL, and cannot find out whether it has no value.
3. Use ='' or <>'' to deal with the judgment of no value. <> represents not equal to.
4. When counting the number of rows in the specified field through count(), if it encounters a NULL value, it will be automatically ignored, and if it encounters no value, it will be added to the record for calculation.

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;

insert image description here
insert image description here
insert image description here
insert image description here

1.6 Regular expressions

match pattern describe example
^ start character of matching text '^bd' matches a string starting with bd
$ Matches the end character of the text 'qn$' matches strings ending with qn
. matches any single character 's.t' matches any string with a character between s and t
* matches zero or more of the characters preceding it 'fo*t' matches t preceded by any o
+ Matches the preceding character 1 or more times 'hom+' matches a string starting with ho followed by at least one m
string matches the specified string 'clo' matches strings containing clo
p1|p2 matches p1 or p2 'bg|fg' matches bg or fg
[…] Matches any character in the character set '[abc]' matches a or b or c
[^…] matches any character not in parentheses '[^ab]' matches a string that does not contain a or b
{n} Match the preceding string n times 'g{2}' matches a string containing 2 g
{n,m} Matches the preceding string at least n and at most m times 'f{1,3}' matches f at least 1 time and at most 3 times
语法: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';

insert image description here

Second, the stored procedure

2.1 Stored procedure definition

  • A stored procedure is a set of SQL statements to complete a specific function.
  • In the process of using the stored procedure, common or complex work is 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 than traditional SQL in execution.

2.2 Advantages of stored procedures

1. After one execution, the generated binary code will be stored in the buffer to improve execution efficiency.
2. The SQL statement plus the set of control statements has high flexibility.
3. It is stored on the server side, and the network load is reduced when the client calls
it.4 , Can be called repeatedly, can be modified at any time, without affecting the client call
5, can complete all database operations, and can also control the information access rights of the database

2.3 Stored procedure application

2.3.1 Stored procedure creation

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

2.3.1 Call stored procedure

call proc;

insert image description here

2.3.2 View stored procedures

SHOW CREATE PROCEDURE [数据库.]存储过程名;		#查看某个存储过程的具体信息

SHOW CREATE PROCEDURE Proc;

SHOW PROCEDURE STATUS [LIKE '%Proc%'] \G

insert image description here
insert image description here

2.3.3 Parameters of stored procedures

1. IN input parameter: indicates that the caller transfers a value to the procedure (incoming value can be a literal or a variable)
2. OUT output parameter: indicates that the procedure transmits a value to the caller (can return multiple values) (outgoing value It can only be a variable)
3. INOUT input and output parameters: not only means that the caller passes in a value to the procedure, but also means that the procedure sends a value to the caller (the value can only be a variable)

DELIMITER $$				
CREATE PROCEDURE Proc1(IN inname CHAR(16))		
-> BEGIN					
-> SELECT * FROM store_info WHERE Store_Name = inname;
-> END $$					
DELIMITER ;					

CALL Proc1('Boston');


delimiter $$
mysql> create procedure proc3(in myname char(10), out outname int)
    -> begin
    -> select sales into outname from t1 where name = myname;
    -> end $$
delimiter ;
call proc3('yzh', @out_sales);
select @out_sales;


delimiter $$
mysql> create procedure proc4(inout insales int)
    -> begin
    -> select count(sales) into insales from t1 where sales < insales;
    -> end $$
delimiter ;
set @inout_sales=1000;
call proc4(@inout_sales);
select @inout_sales;

insert image description here
insert image description here
insert image description here
insert image description here

2.3.4 Delete stored procedure

  • The method of modifying the content of the stored procedure is by deleting the original stored procedure, and then creating a new stored procedure with the same name. If you want to modify the name of the stored procedure, you can delete the original stored procedure first, and then create a new stored procedure with a different name.
DROP PROCEDURE IF EXISTS Proc;		#仅当存在时删除,不添加 IF EXISTS 时,如果指定的过程不存在,则产生一个错误

insert image description here

2.3.5 Control Statements of Stored Procedures

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

(1)条件语句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)循环语句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;

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/2301_76875445/article/details/131331554