MySQL database - advanced query statement

1. Database query

A database is a tool used to store, update, and query data, and querying data is the core function of a database. The database is used to carry information, and the information is used for analysis and viewing. Therefore, it is necessary to master a more refined query method. This article will focus on advanced query statements for data.

2. Efficient query method

1. Specify the field to query - SELECT

Syntax: SELECT "字段" FROM "表名";
Example: SELECT Store_Name FROM fxk002;
insert image description here

2. Perform deduplication query on the field - DISTINCT

Syntax: SELECT DISTINCT "字段" FROM "表名";
Example: SELECT DISTINCT Store_Name FROM fxk003;

insert image description here

3. Condition query - where

Syntax: SELECT "字段" FROM "表名" WHERE "条件";
Example: SELECT Store_Name FROM fxk002 WHERE Sales > 1000;
insert image description here

3. Increase query of logical relationship - and and or

语法:SELECT "字段" FROM "表名" WHERE "条件1" {[AND|OR] "条件2"}+ ;
例:SELECT Store_Name FROM fxk003 WHERE Sales > 1000 OR (Sales < 500 AND Sales > 200);
insert image description here

4. Data record query of known value - IN

语法:SELECT "字段" FROM "表名" WHERE "字段" IN ('值1', '值2', ...);
例:SELECT * FROM fxk003 WHERE Store_Name IN (‘Los Angeles’, ‘Houston’);
insert image description here

5. Data record query within the range - BETWEEN

Syntax: SELECT "字段" FROM "表名" WHERE "字段" BETWEEN '值1' AND '值2';
Example: SELECT * FROM fxk003 WHERE Date BETWEEN '2020-12-06' AND '2020-12-10';
insert image description here

6. Wildcard query

Usually wildcards are used together with LIKE

wildcard illustrate
% A percent sign means zero, one or more characters
_ Underscores represent single characters

LIKE——match a pattern to find the data records we want
Syntax: SELECT "字段" FROM "表名" WHERE "字段" LIKE {模式};
Example: SELECT * FROM fxk003 WHERE Store_Name like '%on%';

insert image description here

7. Keyword sorting query - ORDER BY

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

insert image description here

3. Function query

1. Commonly used mathematical functions in the database

math function effect
abs(x) returns the absolute value of x
rand() Returns a random number between 0 and 1
mod(x,y) Returns the remainder after dividing x by y
power(x,y) returns x to the power of y
round(x) returns the integer closest to x
round(x,y) Rounded value with x to y decimal places
sqrt(x) returns the square root of x
truncate(x,y) Returns the value of the number x truncated to y decimal places
ceil(x) returns the smallest integer greater than or equal to x
floor(x) returns the largest integer less than or equal to x
greatest(x1,x2…) Returns the largest value in the collection, and can also return the largest value of multiple fields
least(x1,x2…) Returns the smallest value in the collection, and can also return the smallest value of multiple fields

insert image description here

2. Aggregation function:

aggregate function effect
avg() Returns the mean 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 the sum of all values ​​in the specified column

insert image description here

3. String function:

string functions effect
trim() Returns the value with the specified format removed
concat(x,y) Concatenate the provided parameters x and y into a string
substr(x,y) Get the string starting from the yth position in the string x, which has the same effect as the substring() function
substr(x,y,z) Gets a string of length z starting at position y in string x
length(x) Returns the length of the string x
replace(x,y,z) substitute the string z for the string y in the string x
upper(x) convert all letters of the string x to uppercase
lower(x) Convert all letters of the string x to lowercase
left(x,y) Returns the first y characters of the string x
right(x,y) Returns the last y characters of the string x
repeat(x,y) repeat the string x y times
space(x) returns x spaces
strcmp(x,y) Compare x and y, the returned value can be -1,0,1
reverse(x) reverse the string x
1. Remove character trim
1.去除字符 trim
语法格式:SELECT TRIM ([ [位置] [要移除的字符串] FROM ] 字符串);
#[位置]:的值可以为 LEADING (起头), TRAILING (结尾), BOTH (起头及结尾)。 
#[要移除的字符串]:从字串的起头、结尾,或起头及结尾移除的字符串。缺省时为空格。

2. 截取 substr
语法格式:SELECT substr(x,y)    #截取x字符串 从第y个开始,截取到末尾

3.字段拼接 concat
语法格式: select concat(字段1,字段2) from 表名;
使用 || 符号
将info表中,name字段值和height字段值拼接在一起。
语法格式: select 字段1 || 字段2 from 表名;

将info表中,name字段值和height字段值拼接在一起,且中间加空格。
语法格式: select 字段1 || ' ' || 字段2 from 表名;

4.返回字符长度 length 
语法格式: select length(字段1) from 表名;

5.替换 replace
select replace(字段1,'替换前字符段','替换后字符段') from 表名;

insert image description here
insert image description here

4. Advanced query statement

1. Grouping and summarizing - GROUP BY

Summarize and group the query results of the fields behind GROUP BY, which is usually used in combination with aggregate functions. There is
a principle in GROUP BY that all fields that appear after GROUP BY must appear after SELECT;
all fields that appear after SELECT and Fields that do not appear in aggregate functions must appear after GROUP BY

语法:SELECT "字段1", SUM("字段2") FROM "表名" GROUP BY "字段1";
例:SELECT Store_Name, SUM(Sales) FROM fxk003 GROUP BY Store_Name ORDER BY sales;
insert image description here

2.过滤——HAVING

用来过滤由 GROUP BY 语句返回的记录集,通常与 GROUP BY 语句联合使用
HAVING 语句的存在弥补了 WHERE 关键字不能与聚合函数联合使用的不足。

语法:SELECT "字段1", SUM("字段2") FROM "表格名" GROUP BY "字段1" HAVING (函数条件);
例:SELECT Store_Name, SUM(Sales) FROM fxk003 GROUP BY Store_Name HAVING SUM(Sales) > 1500;
insert image description here

3.别名设置

----字段別名 表格別名
语法:SELECT "表格別名"."字段1" [AS] "字段別名" FROM "表格名" [AS] "表格別名";
例:SELECT A.Store_Name Store, SUM(A.Sales) “Total Sales” FROM fxk003 A GROUP BY A.Store_Name;
insert image description here

4.子查询

连接表格,在WHERE 子句或 HAVING 子句中插入另一个 SQL 语句
语法:SELECT "字段1" FROM "表格1" WHERE "字段2" [比较运算符] 外查询
(SELECT "字段1" FROM "表格2" WHERE "条件"); 内查询
insert image description here

5.EXISTS

用来测试内查询有没有产生任何结果,类似布尔值是否为真
#如果有的话,系统就会执行外查询中的SQL语句。若是没有的话,那整个 SQL 语句就不会产生任何结果。
语法:SELECT "字段1" FROM "表格1" WHERE EXISTS (SELECT * FROM "表格2" WHERE "条件");
例:SELECT SUM(Sales) FROM fxk003 WHERE EXISTS (SELECT * FROM fxk002 WHERE Region = ‘West’);
insert image description here

五、表连接查询

MYSQL数据库中常用的表连接有三种

1.inner join(内连接)

只返回两个表中联结字段相等的行
insert image description here
语法:select * from 表1 A inner join 表2 B on A.字段 = B.字段;

insert image description here

2.left join(左连接)

返回包括左表中的所有记录和右表中联结字段相等的记录

insert image description here
语法:select * from 表1 A left join 表2 B on A.字段 = B.字段;

insert image description here

3.right join(右连接)

:返回包括右表中的所有记录和左表中联结字段相等的记录
insert image description here
语法:select * from 表1 A right join 表2 B on A.字段 = B.字段;
insert image description here

六、视图的运用—— view

视图:可以被当作是虚拟表或存储查询。

  • 视图跟表格的不同是,表格中有实际储存数据记录,而视图是建立在表格之上的一个架构,它本身并不实际储存数据记录。
  • 临时表在用户退出或同数据库的连接断开后就自动消失了,而视图不会消失。
  • 视图不含有数据,只存储它的定义,它的用途一般可以简化复杂的查询。比如你要对几个表进行连接查询,而且还要进行统计排序等操作,写SQL语句会很麻烦的,用视图将几个表联结起来,然后对这个视图进行查询操作,就和对一个表查询一样,很方便。

语法格式:
创建视图表:CREATE VIEW "视图表名" AS "SELECT 语句";
删除视图表: DROP VIEW "视图表名";

insert image description here

七、联级——UNION

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

UNION ALL :将生成结果的数据记录值都列出来,无论有无重复
语法:[SELECT 语句 1] UNION ALL [SELECT 语句 2];
insert image description here

八、交集值 ----取两个SQL语句结果的交集

1.联级视图求交集值

create view v_info as select distinct name from info union all select distinct name from info3;
select name,count(*) from v_info group by name;
select name from v_info group by name having count(*) >1;

insert image description here

2.内连接求交集值

select A.name from info A inner join info3 B on A.name=B.name;

select A.name from info A inner join info3 B using(name);
insert image description here

3.使用子查询的方式求交集值

insert image description here

4.取非交集值

  1. 联级方法中 count(*)<=1
  2. 左右内连接 将is not null 改为 is null
  3. 子查询 外连接查询 not in (内连接查询)

九、case 条件选择查询语句

 SELECT CASE ("字段名")
     WHEN "条件1" THEN "结果1"
     WHEN "条件2" THEN "结果2"
     [ELSE "结果N"]
     END
 FROM "表名";
     
 # "条件"可以是一个数值或是公式。ELSE子句则并不是必须的

insert image description here

十、正则表达式

匹配模式 描述 实例
^ 匹配文本的开始字符 ‘^bd’ 匹配以 bd 开头的字符串
$ 匹配文本的结束字符 ‘qn$’ 匹配以 qn 结尾的字符串
. 匹配任何单个字符 ‘s.t’ 匹配任何 s 和 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
字符串 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

grammar:SELECT "字段" FROM "表名" WHERE "字段" REGEXP {模式};

insert image description here

Guess you like

Origin blog.csdn.net/weixin_67300995/article/details/131347229