Mysql advanced statements (advanced query statements, database functions, connection queries)

1. mysql query statement

First create the lilade database, and then create the nba table and cba table for testing.

create  database lilade;

create table  lilade.nba (id int,name char(4), age int, sex char(2), hobby varchar(20));

create table  lilade.cba (id int,name char(4), age int, sex char(2), hobby varchar(20));

Insert image description here

1.1. select ---- display all data records of one or several fields in the table

语法
select "字段" from "表名";
例子
select * from nba;

Insert image description here

select name from nba;

Insert image description here

1.2. distinct ---- does not display duplicate data records

语法
select distinct "字段" from "表名"
#例子
select distinct name from nba;

Insert image description here

1.3. where ---- conditional query

where is a conditional query on the source statement.

语法
select "字段" from "表名" where "条件";
#例子
select store_name from laozi where sales > 1000;

Insert image description here

1.4. and or ----and or

语法
select "字段" from "表名" where "条件1" {
    
    [and|or] "条件2"}+ ;
#例子
select store_name from laozi where sales > 1000 or (sales < 500 and sales > 200);

Insert image description here

1.5, in----show data records with known values

语法
select "字段" from "表名" where "字段" in ('值1', '值2', ...);
#例子
select * from laozi where store_name in ('los angeles', 'houston');

Insert image description here

1.6. between----display data records within two value ranges

语法:select "字段" from "表名" where "字段" between '值1' and '值2';
#例子
select * from laozi where date between '2020-12-06' and '2020-12-10';

Insert image description here

1.7. Wildcard

#语法:
select 字段名  from 表名 where 字段 like 模式
wildcard meaning
% Represents zero, one or more characters
_ Underscore represents a single character
A_Z All strings starting with A and ending with Z 'ABZ' 'ACZ' 'ACCCCZ' are not in the range. The underscore only represents one character AZ and contains a space and z.
ABC% All strings ABCD ABCABC starting with ABC
%CBA All strings ending with CBA WCBA CBACBA
%AN% All strings containing AN los angeles
_AN% All strings whose second letter is A and whose third letter is N

1.8, like ---- fuzzy matching

  • Generally used in conjunction with wildcards.
  • Fuzzy matching will scan the entire table by default, and the index will not take effect.
语法
select "字段" from "表名" where "字段" like {
    
    模式};
#例子
select * from laozi where store_name like '%os%';

Insert image description here

1.9 、order by

Sort by keyword

语法
select "字段" from "表名" [where "条件"] order by "字段" [asc, desc];
#asc 是按照升序进行排序的,是默认的排序方式。
#desc 是按降序方式进行排序。
#例子
select store_name,sales,date from laozi order by sales desc;

Insert image description here

1.10, group by ---- summary grouping

  • Summarize and group the query results of the fields following group by, which is usually used in conjunction with aggregate functions.

  • Group by has a principle: all fields that appear after group by must appear after select;

  • All fields that appear after select and do not appear in the aggregate function must appear after group by.

语法
select "字段1", sum("字段2") from "表名" group by "字段1";
#例子
select store_name, sum(sales) from laozi group by store_name order by sales desc;

Insert image description here

select store_name,count(store_name) from laozi group by store_name;

Insert image description here

1.11、 having

  • Perform conditional filtering on the results of the group by statement.

  • Used to filter the record set 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 shortcoming that the where keyword cannot be used in conjunction with aggregate functions.

语法
select "字段1", sum("字段2") from "表格名" group by "字段1" having (函数条件);
#举个例子
select store_name, sum(sales) from laozi group by store_name having sum(sales) > 1500;

Insert image description here

1.12. Alias----field alias, table alias

as can be omitted and will only take effect in the current SQL statement.

语法
select "表格別名"."字段1" [as] "字段別名" from "表格名" [as] "表格別名";
#例子
select a.store_name store, sum(a.sales) as "total sales" from laozi as a group by a.store_name;

Insert image description here

1.13, subquery statement

Join the table and insert another sql statement in the where clause or having clause.

语法
select "字段1" from "表格1" where "字段2" [比较运算符] (select "字段1" from "表格2" where "条件");
#外查询	(#内查询)
#内查询的结果,作为外查询的参数

[比较运算符]
#可以是符号的运算符,例如 =、>、<、>=、<= 
#也可以是文字的运算符,例如 like、in、between
#例子
select sum(sales) from laozi where store_name in (select store_name from location where region = 'West');

Insert image description here

#举个例子2
select sum(A.sales) from laozi as A where A.store_name in (select store_name from location as B where B.store_name = A.store_name);
#store_info表 别名为A表,在当前语句中,可以直接用a代替store_info使用
#location表 别名为B表

Insert image description here

1.14、exists

  • Used to test whether the inner query produces any results.

  • If so, the system will execute the sql statement in the external query;

  • If not, the entire SQL statement will not produce any results.

语法
select "字段1" from "表格1" where exists (select * from "表格2" where "条件";
#例子
select sum(sales) from laozi where exists (select * from location where region = 'West');

select sum(sales) from laozi where exists (select store_name from location where region ='Westt');

Insert image description here

2. MySQL database functions

2.1. Mathematical functions

Math functions Function
abs(x) Returns the absolute value of x
rand() Returns a random number from 0 to 1
mod(x,y) Returns the remainder after dividing x by y
power(x,y) Returns x raised to the y power
round(x) Returns the nearest integer to x
round(x,y) Keep the value of x rounded 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 maximum value in the collection, or the maximum value of multiple fields.
least(x1,x2…) Returns the smallest value in the collection, or the smallest value of multiple fields.
select abs(-1), rand(), mod(5,3), power(2,3), round(1.89);

Insert image description here

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

2.2. Aggregation function

aggregate function Function
avg() Returns the average of the specified column
count(field) Returns the number of non-NULL values ​​in the specified column (number of rows)
count(*) Returns the number of all rows in the specified column, NULL values ​​are not ignored
min( ) Returns the minimum value of the specified column
max( ) Returns the maximum value of the specified column
sum(x) Returns all values ​​in the specified column
select avg(sales) from laozi;

Insert image description here

select count(store_name) from laozi;

Insert image description here

select count(distinct store_name) from laozi;

Insert image description here

select max(sales) from laozi;

Insert image description here

select min(sales) from laozi;

Insert image description here

select sum(sales) from laozi;

Insert image description here

2.3. String function

String functions Function
trim() Returns the value without the specified format
concat(x,y) Concatenate the provided parameters x and y into a string
substr(x,y) Get the string starting from the y-th position in the string x, which has the same effect as the substring() function
substr(x,y,z) Get a string of length z starting from the y-th position in the string x
length(x) Returns the length of string x
replace(x,y,z) Replace, replace string z with string y in string x
upper(x) Convert all letters of string x to uppercase letters
lower(x) Convert all letters of string x to lowercase letters
left(x,y) Returns the first y characters of string x
right(x,y) Returns the last y characters of string x
repeat(x,y) Repeat string x y times
space(x) Return x spaces
strcmp(x,y) Compare x and y, the returned value can be -1,0,1
reverse(x) Reverse the string x

1)trim

#示例1:从名字开头的开始,移除Sun Dasheng中的Sun显示
select trim(leading ‘Sun’ from ‘Sun Dasheng’);
select trim([ [位置] [要移除的字符串] from ] 字符串);
#[位置]:的值可以为 leading (起头), trailing (结尾), both (起头及结尾)。 
#[要移除的字符串]:从字串的起头、结尾,或起头及结尾移除的字符串。缺省时为空格。

#子查询语句,select 嵌套select

select trim(leading 'Los' from (select store_name from location where store_name='Los Angeles'));

select trim( trailing 'York' from (select store_name from location where store_name='New York'));

Insert image description here
2)concat

字段名 不要加 ' '
字符串 要加' '
select concat (region ,' ',store_name) from location;

Insert image description here

select region|| ' ' || store_name from location;

Insert image description here
3)substr

select substr(store_name,5) from location where store_name ='Los Angeles';


select substr(store_name,5,6) from location where store_name ='Los Angeles';

Insert image description here
4)length

 select replace(region,'stern','st'),store_name,length(store_name) from location;

Insert image description here
5)replace

select replace (region,'st','stern') from location;

Insert image description here

3. Connection query

3.1. Table connection

surface connect Overview
inner join Inner joins only return rows with equal join fields in the two tables.
left join left join Returns all records in the left table that are equal to the join fields in the right table, and returns NULL for the unequal parts.
right join right join Returns all records in the right table that are equal to the join fields in the left table, and returns NULL for the unequal parts.
union Union Combine the results of two select query statements and remove duplicates
union all Union Merge the results of two select query statements without deduplication

3.2, union statement

  • Union combines the results of two SQL statements. The fields generated by the two SQL statements need to be of the same data record type.

  • union: The resulting data record values ​​will have no duplicates and will be sorted according to the order of the fields.

语法
[select 语句 1] union [select 语句 2];
select store_name from location union select store_name from laozi;

Insert image description here

union all :将生成结果的数据记录值都列出来,无论有无重复
语法
[select 语句 1] union all [select 语句 2];
select store_name from location union all select store_name from laozi;

Insert image description here

3.3. Multi-table query to find intersection value

Take the intersection of the results of two SQL statements.

基本语法
select A.字段 from 左表 A inner join 右表 B on A.字段 = B.字段;
select A.字段 from 左表 A inner join 右表 B using(同名字段);

select A.字段 from 左表 A, 右表 B where A.字段 = B.字段;

select A.字段 from 左表 A where A.字段 in (select B.字段 from 右表 B);

select A.字段 from 左表 A left join 右表 B on A.字段 = B.字段 where B.字段 is not null;
select B.字段 from 左表 A right join 右表 B on A.字段 = B.字段 where A.字段 is not null;

#求交集
#方式一
select A.store_name from location A inner join laozi B on A.store_name = B.store_name;

Insert image description here

#方式二
select A.store_name from location A inner join laozi B using (store_name);

Insert image description here

#取两个SQL语句结果的交集,且没有重复
select distinct A.store_name from location A inner join laozi B on A.store_name = B.store_name;

select distinct A.store_name from location A inner join laozi B using (store_name);

Insert image description here

select distinct A.store_name from location A inner join laozi B using (store_name) where B.store_name is not NULL;

Insert image description here

select A.store_name from (select distinct store_name from location union all select distinct store_name from laozi) A group by A.store_name having count( *) > 1;

#首先,子查询`select distinct store_name from location`从“location”表中选择所有不重复的店铺名称。
#然后,子查询`select distinct store_name from store_info`从“store_info”表中选择所有不重复的店铺名称。
#使用`union all`将两个子查询的结果合并,并作为临时表A。
#最后,对临时表A按照店铺名称进行分组,使用`having count(*) > 1`筛选出出现次数大于1的店铺名称。

Insert image description here

3.4. Multi-table query to find non-intersection values

显示第一个SQL语句的结果,且与第二个SQL语句没有交集的结果,且没有重复。
求左表无交集
select A.字段 from 左表 A left join 右表 B on A.字段 = B.字段 where B.字段 is null;

select 字段 from 左表 where 字段 not in (select 字段 from 右表);

求右表无交集
select B.字段 from 左表 A right join 右表 B on A.字段 = B.字段 where A.字段 is null;

select 字段 from 右表 where 字段 not in (select 字段 from 左表);

求多表的无交集
select A.字段 from (select distinct 字段 from 左表 union all select distinct 字段 from 右表) A group by A.字段 having count(A.字段)=1;

select distinct store_name from location where (store_name) not in ( select store_name from laozi);

#子查询`select store_name from store_info`从"store_info"表中选择所有的店铺名称。
#主查询`select distinct store_name from location`从"location"表中选择所有不重复的店铺名称。
#使用`where (store_name) not in`条件将主查询中的店铺名称过滤掉那些在子查询结果中出现的店铺名称。

Insert image description here

select distinct A.store_name from location A left join laozi B using (store_name) where B.store_name is NULL;

#使用`left join`将"location"表(作为左表,记为A)和"store_info"表(作为右表,记为B)按照店铺名称进行连接。
#使用`using (store_name)`条件指定以店铺名称为连接的字段。
#使用`where B.store_name is NULL`条件过滤掉在连接结果中,店铺名称在"location"表中出现但在"store_info"表中没有匹配的记录。
#最后,使用`distinct`关键字来返回不重复的店铺名称。


Insert image description here

select A.store_name from (select distinct store_name from location union all select distinct store_name from laozi) as A group by A.store_name having count(*)=1;

#子查询`select distinct store_name from location`从"location"表中选择所有不重复的店铺名称。
#子查询`select distinct store_name from store_info`从"store_info"表中选择所有不重复的店铺名称。
#使用`union all`将两个子查询的结果合并。
#将合并结果作为临时表A,并使用`as A`来给临时表起一个别名。
#在临时表A的基础上,使用`group by A.store_name`对店铺名称进行分组。
#使用`having count(*) = 1`筛选出出现次数为1的店铺名称。

Insert image description here

4. SQL statement execution sequence

FROM
<left table>

ON
<join_condition>
<join_type>

JOIN
<right_table>

WHERE
<where condition>

GROUP BY
<group_by_list>

HAVING
<having_condition>

SELECT

DISTINCT
<select list>

ORDER BY
<order_by_condition>

LIMIT
<limit number>

########################################################################################################
在SQL中,一般而言,SQL查询语句的执行顺序如下:

1. FROM:指定要查询的数据表或视图。
2. JOIN:根据指定的条件连接多个表。
3. WHERE:基于指定的条件筛选出符合要求的行。
4. GROUP BY:按照指定的列进行分组。
5. HAVING:对分组后的结果进行条件筛选。
6. SELECT:选择要返回的列。
7. DISTINCT:去除重复的行。
8. ORDER BY:按照指定的列进行排序。
9. LIMIT/OFFSET:限制返回的结果数量和起始位置。

summary


```go
order by 字段 ASC|DESC                 #排序
group by 字段                          #分组
group by 字段 having 条件表达式        #根据group by分组后的结果再进行条件过滤

表连接
inner join    内连接,只返回两个表的字段相等的行记录
left join     左连接,返回左表所有的行记录和右表字段相等的行记录,不相等的行返回NULL
right join    右连接,返回右表所有的行记录和左表字段相等的行记录,不相等的行返回NULL
union         联集,将两个select查询语句的结果合并,并去重
union all     联集,将两个select查询语句的结果合并,不去重


求交集
select A.字段 from 左表 A inner join 右表 B on A.字段 = B.字段;
select A.字段 from 左表 A inner join 右表 B using(同名字段);

select A.字段 from 左表 A, 右表 B where A.字段 = B.字段;

select A.字段 from 左表 A where A.字段 in (select B.字段 from 右表 B);

select A.字段 from 左表 A left join 右表 B on A.字段 = B.字段 where B.字段 is not null;
select B.字段 from 左表 A right join 右表 B on A.字段 = B.字段 where A.字段 is not null;


求左表无交集
select A.字段 from 左表 A left join 右表 B on A.字段 = B.字段 where B.字段 is null;

select 字段 from 左表 where 字段 not in (select 字段 from 右表);

求右表无交集
select B.字段 from 左表 A right join 右表 B on A.字段 = B.字段 where A.字段 is null;

select 字段 from 右表 where 字段 not in (select 字段 from 左表);

求多表的无交集
select A.字段 from (select distinct 字段 from 左表 union all select distinct 字段 from 右表) A group by A.字段 having count(A.字段)=1;


Guess you like

Origin blog.csdn.net/fyb012811/article/details/133307572