Advanced SQL statement

MySQL Advanced (Advanced) SQL Statements

---- SELECT ----
Display all data records of one or several fields in the table
Syntax: SELECT "field" FROM "table name";

SELECT Store_Name FROM Store_Info;

---- DISTINCT ----
Do not display duplicate data records
Syntax: SELECT DISTINCT "field" FROM "table name";

SELECT DISTINCT Store_Name FROM Store_Info;

---- WHERE ----
conditional query
Syntax: SELECT "field" FROM "table name" WHERE "condition";

SELECT Store_Name FROM Store_Info WHERE Sales > 1000;

---- AND OR ----
and or
Syntax: SELECT "field" FROM "table name" WHERE "condition 1" {[AND|OR] "condition 2"}+ ;

SELECT Store_Name FROM Store_Info WHERE Sales > 1000 OR (Sales < 500 AND Sales > 200);

---- IN ----
Display data records of known values
​​Syntax: SELECT "field" FROM "table name" WHERE "field" IN ('value1', 'value2', …);

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

----BETWEEN ----
Display data records within two value ranges
Syntax: SELECT "field" FROM "table name" WHERE "field" BETWEEN 'value 1' AND 'value 2';

SELECT * FROM Store_Info WHERE Date BETWEEN '2020-12-06' AND '2020-12-10';

---- 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' 则不符合这个模式。

---- LIKE ----
Match a pattern to find the data records we want
Syntax: SELECT "field" FROM "table name" WHERE "field" LIKE {pattern};

SELECT * FROM Store_Info WHERE Store_Name like '%os%';

---- ORDER BY ----
Sort by keyword
Syntax: SELECT "field" FROM "table name" [WHERE "condition"] ORDER BY "field" [ASC, DESC];

#ASC 是按照升序进行排序的,是默认的排序方式。
#DESC 是按降序方式进行排序。
SELECT Store_Name,Sales,Date FROM Store_Info ORDER BY Sales DESC;

function

Mathematical functions:

abs(x)				返回 x 的绝对值
rand()				返回 0 到 1 的随机数
mod(x,y)			返回 x 除以 y 以后的余数
power(x,y)			返回 x 的 y 次方
round(x)			返回离 x 最近的整数
round(x,y)			保留 x 的 y 位小数四舍五入后的值
sqrt(x)				返回 x 的平方根
truncate(x,y)		返回数字 x 截断为 y 位小数的值
ceil(x)				返回大于或等于 x 的最小整数
floor(x)			返回小于或等于 x 的最大整数
greatest(x1,x2...)	返回集合中最大的值,也可以返回多个字段的最大的值
least(x1,x2...)		返回集合中最小的值,也可以返回多个字段的最小的值
例:
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);

insert image description here
insert image description here

aggregate function

avg() Returns the average value of the specified column
count() Returns the number of non-NULL values ​​in the specified column
min() Returns the minimum value of the specified column
max() Returns the maximum value of the specified column
sum(x) Returns all values ​​​​of the specified column Sum

例:
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;
········································
City表 
+----------+
| name     |
|----------|
| beijing  |
| nanjing  |
| shanghai |
| <null>   |
| <null>   |
+----------+
SELECT count(name) FROM City;
SELECT count(*) FROM City;
#count(*) 包括了所有的列的行数,在统计结果的时候,不会忽略列值为 NULL
#count(列名) 只包括列名那一列的行数,在统计结果的时候,会忽略列值为 NULL 的行

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

String functions:

trim()			 	返回去除指定格式的值
concat(x,y)			将提供的参数 x 和 y 拼接成一个字符串
substr(x,y)			获取从字符串 x 中的第 y 个位置开始的字符串,跟substring()函数作用相同
substr(x,y,z)		获取从字符串 x 中的第 y 个位置开始长度为 z 的字符串
length(x)			返回字符串 x 的长度
replace(x,y,z)		将字符串 z 替代字符串 x 中的字符串 y
upper(x)			将字符串 x 的所有字母变成大写字母
lower(x)			将字符串 x 的所有字母变成小写字母
left(x,y)			返回字符串 x 的前 y 个字符
right(x,y)			返回字符串 x 的后 y 个字符
repeat(x,y)			将字符串 x 重复 y 次
space(x)			返回 x 个空格
strcmp(x,y)			比较 x 和 y,返回的值可以为-1,0,1,x > y 返回 1,x = y 返回0, x < y 返回-1
reverse(x)			将字符串 x 反转
SELECT concat(Region, Store_Name) FROM location WHERE Store_Name = 'Boston';

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

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

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

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

SELECT Region,length(Store_Name) FROM location;

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

insert image description here
insert image description here

---- GROUP BY ----
Summarize and group the query results of the fields behind GROUP BY, usually combined with aggregate functions. There is
a principle in GROUP BY, all fields that appear after GROUP BY must be behind SELECT appears;
any field that appears after SELECT and does not appear in the aggregate function must appear after GROUP BY

Syntax: SELECT "Field 1", SUM("Field 2") FROM "Table Name" GROUP BY "Field 1";

SELECT Store_Name, SUM(Sales) FROM Store_Info GROUP BY Store_Name ORDER BY sales desc;

insert image description here

---- HAVING ----
Used to filter the recordset returned by the GROUP BY statement, usually used in conjunction with the GROUP BY statement. The
existence of the HAVING statement makes up for the deficiency that the WHERE keyword cannot be used in conjunction with the aggregate function.
Syntax: SELECT "Field 1", SUM("Field 2") FROM "Table Name" GROUP BY "Field 1" HAVING (function condition);

SELECT Store_Name, SUM(Sales) FROM store_info GROUP BY Store_Name HAVING SUM(Sales) > 1500;

insert image description here

---- Alias ​​----
field alias table alias
Syntax: SELECT "table alias". "field 1" [AS] "field alias" FROM "table name" [AS] "table alias";

SELECT A.Store_Name Store, SUM(A.Sales) "Total Sales" FROM store_info A GROUP BY A.Store_Name;

insert image description here

---- Subquery ----
Join tables, insert another SQL statement in WHERE clause or HAVING clause Syntax
: SELECT "Field 1" FROM "Table 1" WHERE "Field 2" [comparison operator] # Outer query
(SELECT "field 1" FROM "table 2" WHERE "condition"); #inner query

#It can be a symbolic operator, such as =, >, <, >=, <=; it can also be a literal operator, such as LIKE, IN, BETWEEN SELECT SUM(Sales) FROM Store_Info WHERE Store_Name IN (
SELECT Store_Name FROM location WHERE Region = 'West');

insert image description here
---- EXISTS ----
Used to test whether the inner query produces any results, similar to whether the Boolean value is true
#If yes, the system will execute the SQL statement in the outer query. If not, then the entire SQL statement will not produce any results.
Syntax: SELECT "Field 1" FROM "Form 1" WHERE EXISTS (SELECT * FROM "Form 2" WHERE "Condition");

sum(sales) from store_info where exists (select * from location where region='west');

insert image description here

connection query

Table A
insert image description here

Table B
insert image description here

Inner join (inner connection):

Return only rows with equal join fields in both tables
insert image description here
insert image description here
Another way of inner join
SELECT * FROM location A, Store_Info B WHERE A.Store_Name = B.Store_Name;
insert image description here

left join (left join):

Returns all records including all records in the left table and the records in the right table with the join field equal
insert image description here
insert image description here

right join (right join):

Returns all records including all records in the right table and the records in the join field of the left table

insert image description here
insert image description here

CREATE VIEW (view)

  • Views, which can be thought of as virtual tables or stored queries.
  • 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

insert image description here

UNION

Union set, combining the results of two SQL statements, the fields generated by the two SQL statements need to 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;

insert image description here

insert image description here

CASE

It is a keyword used by SQL as logic such as 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
insert image description here

The difference between empty value (NULL) and no value ('')

  • The length of no value is 0, which does not take up space; while the length of NULL value is NULL, which takes up space.
  • 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.
  • Use ='' or <>'' to handle the judgment of no value. <> represents not equal to.
  • When using count() to specify the number of rows in the field statistics, if a NULL value is encountered, it will be automatically ignored, and if no value is encountered, it will be added to the record for calculation.
City 表格
+----------+
| 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;

regular expression

匹配模式		描述									实例
^ 				匹配文本的开始字符 						‘^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 次

语法: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';

Guess you like

Origin blog.csdn.net/weixin_60917414/article/details/131316821