MySQL advanced statement

Table of contents

1. Regular expressions

Second, the operator

1. Arithmetic operators

2. Comparison operators

3. Logical operators (boolean values)   

4. Bitwise operators

3. Connection query

 1. Inner join

2. Left join

3. Right join

Fourth, the database function

1. Mathematical functions     

2. Aggregate function

3. String functions 

4. Date and time functions 

Second, the stored procedure

1 Overview

2. Introduction

3. Advantages of stored procedures


1. Regular expressions

        When retrieving database records, MySQL regular expressions usually match special strings that meet the requirements in the records according to the specified matching pattern. The regular expression of MySQL uses the regexp keyword to specify the matching mode of the regular expression, the matching mode supported by the regexp operator.

查询以  开头的信息
select id,name from 表名 where name regexp '^  ';

查询以 结尾的信息
select id,name from 表名 where name regexp ' $';

查询名字中包含  的信息
select id,name from 表名 where name regexp '  ';

查询名字是  开头,  结尾,中间不知道是一个什么字符的信息
select id,name from 表名 where name regexp ' . ';

查询名字中包含  或者 的学生信息
select id,name from 表名 where name regexp '  |  ';

查询名字中有 , 可有可无的学生信息
必须要有的部分是' ’而' '可有可无
select id,name from 表名 where name regexp '  *' ;

查询名字中含有 ,  至少出现一次的学生信息
select id, name from 表名 where name regexp '  +' ;

查询名字以 - 开头的学生信息
select id,name from 表名 where name regexp '^[ - ]';

查询名字不是  的学生信息
select id,name from 表名 where name regexp ' [^  ]';

查询学生名字不以  各字母开头的学生信息
select id,name from 表名 where name regexp '^[^  ]';
match describe
^ matches the start character of the text
$ Matches the end character of the text
. matches any single character
* matches zero or more characters preceding it
% match all
+ Match the preceding character 1 or more times
?
string matches a string containing the specified
p1 | p2 match p1 or p2
[...] matches any character in the set of characters
[^...] matches any character not enclosed in parentheses
[ n ] matches the preceding string n times
[ n,m ] Match the preceding string at least n times and at most m times

Second, the operator

        MySQL operators are used to operate on field values ​​in records. There are four types of operators in MySQL: arithmetic operators, comparison operators, logical operators and bitwise operators.

1. Arithmetic operators

Use the select command to implement the most basic addition, subtraction, multiplication and division operations. MySQL supports the use of arithmetic operators.

operator describe
+ addition
- subtraction
* multiplication
/ division
% remainder

        In division and remainder operations, the divisor cannot be 0. If the divisor is 0, the returned result is NULL. It should be noted that if there are multiple operators, the operations are performed according to the priority of multiplication and division followed by addition and subtraction. Operators with the same priority have no order.

select 1+2,2-1,3*4,4/2,582;
create table 表名 as select 1+2,2-1, 3*2, 4/2, 582;
select * from 表名;

2. Comparison operators

        Comparison operators are one-class operators that are often used when querying data records. By using the comparison operator, you can determine
which records in the table are eligible. If the result of the comparison (returned in the form of a boolean value) is true, it will return 1, if it is false, it will return 0. If the result of the comparison is not Returns NULL if determined. The strings are case-insensitive by default when comparing them. If you want to be case-sensitive, you can use the binary keyword to achieve it.

operator describe
= equal
> more than the
< less than
>= greater or equal to
<= less than or equal to
!= or < > not equal to
is null Check if a value is null
is not null Check if a value is not null
between and in between
in in the collection
like wildcard matching
greatest Returns the maximum value when there are two or more arguments
least Returns the smallest value when there are two or more arguments
regexp regular expression

       The equal sign (=) is used to determine whether numbers, strings, and expressions are equal, returning 1 if they are equal, and 0 if they are not. If one of the two values ​​compared is NULL, the result of the comparison is NULL. The comparison of characters is judged according to the ASCII code. If the ASCII codes are equal, it means that the two characters are the same; if the ASCII codes are not equal, it means that the two characters are not the same.

String (letter) comparison: ('a'>'b') In fact, the comparison is the underlying ASCII code.
What needs to be paid attention to is the ascii code: a, A, 0 (97, 65, 48).
Contrary to the expression of the return value of Linux, the return value of normal operation in Linux is 0, and the return value of abnormal operation is non-0.

select 2=4,2=2,2='2','e'='e','r'=null;

(1) If both are integers, they are compared according to the integer value.
(2) If an integer is a string, the string will be automatically converted to a number and then compared. (In the program, it is generally not to compare the two)
1) If both are integers, compare them according to the integer value.
2) If an integer is a string, the string will be automatically converted to a number and then compared. (In the program, it is generally not to compare the two)
3) If both are strings, compare them according to the strings.
4) If at least one of the two values ​​is NULL, the result of the comparison is NULL.

 

not equal (<>, !=)

       不等于号有两种写法,分别是<>或者!=,用于针对数字、字符串和表达式不相等的比较。如果 不相等则返回1,如果相等则返回0,这点正好跟等于的返回值相反。需要注意的是不等于运算符不能用于判断NULL。

select 'abc'<>'cba' ,2<>2,3!=2, null<>null;

  

大于(>)运算符

       用来判断左侧的操作数是否大于右侧的操作数,若大于返回1,否则返回0,同样不能用于判断NULL。

小于(<)运算符

        用来判断左侧的操作数是否小于右侧的操作数,若小于返回1,否则返回0,同样不能用于判断NULL。
大于等于| (>=)

        判断左侧的操作数是否大于等于右侧的操作数,若大于等于返回1,否则返回0,不能用于判断NULL。
小于等于(<=)

        判断左侧的操作数是否小于等于右侧的操作数,若小于等于返回1,否则返回0,不能用于判断NULL。

select 5>4, 3<4, 'a'<'b' ,4.4<5, 'u'>=null;
select 2 is null, 'a' is not null,null is null;

between and 比较运算通常用于判断一个值是否落在某两个值之间。
判断某数字是否在另外两个数字之间,也可以判断某英文字母是否在另外两个字母之间。

select 4 between 2 and 5,'c' between 'a' and 'b';

between and覆盖的范围是>=和<=关系

least 和greatest (取最小值、取最大值)

least: 当有两个或者多个参数时,返回其中的最小值。如果其中一个值为NULL, 则返回结果就为NULL。
greatest: 当有两个或者多 个参数时,返回其中的最大值。如果其中一 个值为NULL,则返回结果就为NULL。
      若要判断一组数字或字母中哪个最小、哪个最大,可以通过使用LEAST和GREATEST 来实现。

select least (1,2,3),greatest(1,2,3),least('a','b','c'),greatest('a','b','c');

in判断一个值是否在对应的列表中,如果是返回1,否则返回0。
not in 判断一个值是否不在对应的列表中,如果不是返回1,否则返回0

select 1 in (1,2,3),2 not in ('a', 'b', 'c');

like 用来匹配字符串,如果匹配成功则返回1, 反之,返回0
like 支持两种通配符: 'B' 用于匹配任意数目的字符(*匹配的是前面一个字符),而'_'只能匹配一个字符。
not like 正好跟like相反,如果没有匹配成功则返回1,反之返回0。
select 'abc' like 'ab8', 'abc' like '_ bc', 'abc' not like 'a%';

3.逻辑运算符(布尔值)   

       逻辑运算符又被称为布尔运算符,通常用来判断表达式的真假,如果为真返回1, 否则返回0,真和假也可以用true和false表示。MySQL中支持使用的逻辑运算符有四种。

运算符 描述
not或! 逻辑非
and 或 && 逻辑与
or 逻辑或
xor 逻辑异或

(1) 逻辑非
逻辑运算符中最简单的运算符就是逻辑非,逻辑非使用not。
        或 ! 表示。逻辑非将跟在它后面的逻辑测试取反,把真变为假,把假变为真。如果not后面的操作数为0时,所得值为1:如果操作数为非0时,所得值为0:如果操作数为NULL时,所得值为NULL。

select not 2, !3,not 0,! null;

(2) 逻辑与(and)
当所有的操作数都为非0值且不为nul1时,返回值为1,否则为0(null与0比较特殊)

逻辑与使用and 或者 &&表示

select 2 and 3,4 && 0,4 && null,0 and null,null and null;

由结果可看出

and 和&&的作用相同
1 and -1没有0或null,所以返回值为1
1 and 0中由有0,所以返回值为0
1 and null 有Null,所以返回值为null
null and 0返回值为0

(3) 逻辑或(or)
逻辑或通常使用or。
逻辑或表示包含的操作数,任意一个为非零值并且不是NULL值时,返回1,否则返回0。
当有一个操作数为nul1时,如果另一个操作数为非0值,则返回值为1,否则为null。
如两个操作数均为null,则返回值为null。
使用或运算符or进行逻辑判断,运行:

select 2 or 3,2 or 0,2 or null,0 or 0,null or null,0 or null;
select 0 or null or 2;

(4)逻辑异或(xor )
两个非NULL 值的操作数,如果两者都是0或者都是非0,则返回0。
如果一个为0,另一个为非0,则返回结果为1。
当任意一个值为NULL 时,返回值为NULL。

select 2 xor 3,1 xor 0,0 xor null, null xor null;

4.位运算符

       位运算符实际上是对二进制数进行计算的运算符。MySQL内位运算会先将操作数变成二二进制格式(1010   1111),然后进行位运算,最后再将计算结果从二进制变回到十进制格式,方便用户查看。MySQL支持6种位运算符。 

位运算符 描述
& 按位与
| 按位或
~ 按位取反
^ 按位异或
<< 按位左移
>> 按位右移
select 10 & 15,10 | 15,10 ^ 15,5 &~1;

10转换为二进制数是1010, 15转换为二进制数是1111。

        按位与运算(&),是对应的二进制位都是1的,它们的运算结果为1,否则为0,所以10 & 15的结果为10。

        按位或运算(1),是对应的二进制位有一个或两个为1的,运算结果为1,否则为0,所以10 |15的结果为15。
       按位异或运算(^),是对应的二进制位不相同时,运算结果1,否则为0,所以10^15的结果为5。
       按位取反(~),是对应的二进制数逐位反转,即1取反后变为0,0取反后变为1。数字1的二进制是0001,取反后变为1110,数字5的二进制是0101, 将1110 和0101进行求与操作,其结果是_二进制的0100,转换为十进制就是4。
         以上不管哪种运算符,在使用过程中都有优先级问题。运算符的优先级决定了不同的运
算符在计算过程中的先后顺序。级别高的运算符会先进行计算,如果运算符的级别相同,MySQL会按照顺序从左到右依次进行计算,优先级。

优先级 运算符
1 !
2 ~
3 ^
4 *、/、%
5 +,-
6 >>,<<
7 &
8 |
9 =,<=>,>=,>,<=,<,< >,!=,is,like,regexp,in
10 between, case, when, then, else
11 not
12 &&,and
13 ||,or,xor
14 :=

三、连接查询

        MySQL的连接查询, 通常都是将来自两个或多个表的记录行结合起来, 基于这些表之间的共同字段,进行数据的拼接。首先,要确定一个主表作为结果集,然后将其他表的行有选择性的连接到选定的主表结果集上。使用较多的连接查询包括:内连接、左连接和右连接。

create table test1 (
a_id int (11) default null,
a_name varchar(32) default null,
a_level int(11) default null);

create table test2 (
b_id int(11) default null, 
b_name varchar (32) default null,
b_level int(11) default null);
insert into test1 values (1,'aaaa',10);
insert into test1 values (2,'bbbb',20);
insert into test1 values (3,'cccc',30);
insert into test1 values (4,'dddd',40);

insert into test2 values (2,'bbbb',20);
insert into test2 values (3,'cccc',30);
insert into test2 values (5,'eeee',50);
insert into test2 values (6,'ffff',60);

 1.内连接

       MySQL中的内连接就是两张或多张表中同时符合某种条件的数据记录的组合。通常在from子句中使用关键字inner join来连接多张表,并使用ON子句设置连接条件,内连接是系统默认的表连接,所以在from子句后可以省略inner关键字,只使用关键字JOIN。同时有多个表时,也可以连续使用inner join来实现多表的内连接,不过为了更好的性能,建议最好不要超过三个表。

(1)语法

select colunn_name (s) from 表名 inner join 表名 on 表名.column_name = 表名.column_name;


create table 表名 (name varchar(40),score decimal (4,2),address varchar(40));
insert into 表名 values ('wangwu',80,'beijing'),('zhangsan',99,'shanghai'), ('lisi',100, 'nanjing');
select * from 表名; 

select 表名.id, 表名.name from 表名 inner join 表名 on 表名.name-表名.name;

内连查询:通过inner join的方式将两张表指定的相同字段的记录行输出出来

 

 

 

2.左连接

        左连接也可以被称为左外连接,在from子句中使用left join 或者left outer join 关键字来表示。左连接以左侧表为基础表,接收左表的所有行,并用这些行与右侧参考表中的记录进行匹配,也就是说匹配左表中的所有行以及右表中符合条件的行。

select * from 表名 left join 表名 on 表名.name-表名.name; 

左连接中左表的记录将会全部表示出来,而右表只会显示符合搜索条件的记录,右表记录不足的地方均为NULL。

 

 

3.右连接

        右连接也被称为右外连接,在from子句中使用right join或者right outer join关键字来表示。右连接跟左连接正好相反,它是以右表为基础表,用于接收右表中的所有行,并用这些记录与左表中的行进行匹配。

select * from 表名 right join 表名 on 表名.name-表名.name; 

      在右连接的查询结果集中,除了符合匹配规则的行外,还包括右表中有但是左表中不匹配的行,这些记录在左表中以NULL补足。

 

 

四、数据库函数

1.数学函数
     

       数据库内存储的记录,经常要进行一-系列的算术操作,所以MySQL支持很多数学函数。常用的数学函数

数学函数 描述
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...) 返回集合中最小的值
-2的绝对值
select abs(-2);

0-1的随机数(0<-x<1) 
select rand();

可以搭配运算符
select rand() *100;

除以2的余数
select mod(5,2);

2的3次方
select power(2,3);

离1.89最近的整数
select round(1.49);
select round(1.5);

1.893保留小数点后2位,1.896保留小数点后2位,这里会四舍五入
select round(1.893,2);
select round(1.896,2);

返回平方根
select sqrt(4);
select sqrt (5);

保留小数点后2位,但truncate函数不会四舍五入(截断)
select truncate(1.896,2);

返回大于或等于5.2的最小整数
select ceil(5.2);

返回小于或等于5.2的最大整数
select floor(5.2);

返回最大值
select greatest(1,2,3);

返回最小值.
select least (1,2,3);

2.聚合函数

        MySQL数据库函数中专门有一-组函数是特意为库内记录求和或者对表中的数据进行集中概括而设计的,这些函数被称作聚合函数。 

聚合函数 描述
avg () 返回指定列的平均值
count() 返回指定列中非NULL值的个数
min() 返回指定列的最小值
max () 返回指定列的最大值
sum(x) 返回指定列的所有值之和
返回分数的总和
select sum(score) from 表名;

返回分数字段的个数
select count (score) from 表名;

返回分数的最大值
select max(score) from 表名;

返回分数的平均值
select avg (score) from 表名;

 

 

  

3.字符串函数 

字符串函数 描述
length (x) 返回字符串x的长度
trim() 返回字符串x的长度
concat (x,y) 将字符串x的所有字母变成大写字母
upper (x) 将字符串x的所有字母变成大写字母
lower (x) 将字符串x的所有字母变成小写字母
left (x,y) 将字符串x的所有字母变成小写字母
right (x,y) 返回字符串x的后y个字符
repeat (x,y) 将字符串x重复γ次
space (x) 返回x个空格
replace(x,y,z) 将字符串z替代字符串x中的字符串y
strcmp(x, y) 比较x和y,返回的值可以为 -1,0,1
substring(x,y,z) 获取从字符串x中的第y个位置开始长度为z的字符串
reverse (x) 将字符串x反转

length(x) 返回字符串x的长度
返回abcd的长度,空格也算一个字符

select length('abcd');
select length('abcd');

trim()  返回去除格式的值

select trim('     sheng');
select '       sheng';

concat(x,y) 将提供的参数x和y拼接成一个字符串

select concat('abc', 'def');
select concat('abc',' def');

还可以结合其他函数,如trim(将后面的函数删除格式)

select concat('abc',trim('def'));

upper(x) 将字符串x的所有字母变成大写字母

select upper('abc');

lower(x) 将字符串x的所有字母变成小写字母

select lower('ABC');

left (x,y)   返回字符串x的前y个字符

select left('abcdefg',3);
select left('abcdefg',3);

right (x,y)  返回字符串x的后y个字符

select right ('abcdefg',3);

把字符串的前3个字母和后3个字母拼接起来

select concat (left('abcdefg' ,3),right ('abcdefg',3));

repeat(x,y) 将字符串x重复y 次

select repeat ('abc',2);

space(x) 返回x个空格

select length (space(3));

replace(x,y,z)  将字符串z替代字符串x中的字符串y

select replace('hello','ll','aa');

strcmp(x,y) 比较x和y,返回的值可以为-1,0,1

比较17和18,小于返回-1,等于返回0,大于返回1,只会返回这3个值,它是比较第一位不同的数字
select strcmp(17,18);
select strcmp(18,18);
select strcmp(19,18);
select strcmp(17,1);

substring(x,y,z) 获取从字符串x中的第y个位置开始长度为z的字符串,返回从字符串中第三个字符开始的4个字符。

select substring('abcdefg',3,4);

reverse (x)  将字符串x反转

select reverse('gfedcba');

返回字符串的前3个字符,然后反转输出

select reverse (left ('gfedcba',3));

先将字符串反转,再输出前3个字符

select left (reverse ('gfedcba'),3);

4.日期时间函数 

字符串函数 描述
curdate() 返回当前时间的年月日
curt ime{) 返回当前时间的时分秒
now() 返回当前时间的日期和时间
month (x) 返回日期x中的月份值
week (x) 返回日期x是年度第几个星期
hour (x) 返回x中的小时值
minute (x) 返回x中的分钟值
second (x) 返回x中的秒钟值
dayofweek(x) 返回x是星期几,1星期日,2星期一
dayo fmonth (x) 计算日期x是本月的第几天
dayofyear (x) 计算日期x是本年的第几天
返回年月日
select curdate();

返回当前时间
select curtime();

返回当前完整时间
select now();

返回月份
select month('年-月-日');

返回当前日期是一年中的第几周
select week('年-月-日');

返回当前时间的小时
select hour (curtime());

返回当前时间的分钟
select minute (curtime());

返回当前时间的秒
select second (curtime());

当前是星期几
select dayofweek (curdate());

当前日期是本月的第几天
select dayofmonth (curdate());

当前日期是今年的第几天
select dayofyear (curdate());

二、 存储过程

1.概述

        MySQL相关知识都是针对一个表或几个表的单条SQL语句,使用这样的SQL语句虽然可以完成需求,但在实际的数据库应用中,有些数据库操作可能会非常复杂,可能会需要多条SQL语句一起去处理才能够完成,使用存储过程轻松而高效的去完成这个需求,类似shell脚本里的函数。

2.简介

存储过程是一组为了完成特定功能的SQL语句集合。
        存储过程在使用过程中是将常用或者复杂的工作预先使用SQL语句写好并用一个指定的名称存储起来,这个过程经编译和优化后存储在数据库服务器中。当需要使用该存储过程时,只需要调用它即可。存储过程在执行上比传统SQL速度更快、执行效率更高。

3.存储过程的优点

(1)执行一次后,会将生成的二进制代码驻留缓冲区,提高执行效率。
(2) SQL 语句加上控制语句的集合,灵活性高。
(3)在服务器端存储,客户端调用时,降低网络负载。
(4) 可多次重复被调用,可随时修改,不影响客户端调用。
(5)可完成所有的数据库操作,也可控制数据库的信息访问权限。

创建存储过程

delimiter $$ 将语句的结束符号从分号;临时改为两个$$(可以自定义)
create procedure Proc() 创建存储过程,过程名为Proc,不带参数
→begin 过程体以关键字begin开始
→select * from store_info; 过程体语句
→end $$ 过程体以关键字END结束
→delimiter; 将语句的结束符号恢复为分号

调用存储过程

call Proc();

查看存储过程
格式:

show create procedure [ 数据库 ]存储过程名;

查看某个存储过程的具体信息

show create procedure proc\G

查看所有信息

show procedure status [like '%Proc%']\G

查看指定存储过程信息

show procedure status like '%proc%'\G

存储过程的参数
in输入參数:表示调用者向过程传入值(传入值可以是字面量或变量)
out输出參数:表示过程向调用者传出值(可以返回多个值) (传出值只能是变量)
inout输入输出参数:既表示调用者向过程传入值,又表示过程向调用者传出值(值只能是变量)
 

delimitelr @@
create procedure proc2 (in inname varchar (40) )
begin
select * from 表名 where name=inname;
end @@
delimiter @@
call proc2 ('wangwu');

 

 

 

删除存储过程
       存储过程内容的修改方法是通过删除原有存储过程,之后再以相同的名称创建新的存储过程。

drop procedure if exists Proc;

 

 

 

 

 

 

增加内容,仍然会显示。 

 

 

精确匹配查询时若没有则显示NULL

 

Guess you like

Origin blog.csdn.net/Drw_Dcm/article/details/126972427