学习前的准备:先创建两张表,用于语句实验
mysql -uroot -p
show databases;
create database plane;
use plane;
create table destination (
region char(20),
place_name char(20));
insert into destination values(‘southwest’,‘chengdu’);
insert into destination values(‘north China’,‘beijing’);
insert into destination values(‘southwest’,‘kunming’);
insert into destination values(‘north China’,‘tianjin’);
select * from destination;
create table info (
place_name char(20),
sales int(10),
date char(10));
insert into info values(‘chengdu’,‘350’,‘2021-02-10’);
insert into info values(‘beijing’,‘294’,‘2021-02-10’);
insert into info values(‘kunming’,‘330’,‘2021-02-10’);
insert into info values(‘beijing’,‘392’,‘2021-02-16’);
select * from info;
语法:SELECT "栏位" FROM "表名";
例:
select place_name from destination;
语法:SELECT DISTINCT "栏位" FROM "表名";
例:
select distinct place_name from info;
语法:SELECT "栏位" FROM "表名" WHERE "条件";
例:
select place_name from info where sales > 300;
语法:SELECT "栏位" FROM "表名" WHERE "条件1" {[AND|OR] "条件2"}+ ;
例:
select place_name from info where sales > 350 or sales < 300;
select place_name from info where sales > 300 and sales < 350;
语法:SELECT "栏位" FROM "表名" WHERE "栏位" IN ('值1', '值2', ...);
例:
select * from info where place_name in ('beijing');
select * from info where place_name in ('beijing','kunming');
语法:SELECT "栏位" FROM "表名" WHERE "栏位" BETWEEN '值1' AND '值2';
例:
select * from info where sales between '300' and '350';
% :百分号表示零个、一个或多个字符
_ :下划线表示单个字符
例:
'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' 则不符合这个模式。
语法:SELECT "栏位" FROM "表名" WHERE "栏位" LIKE {模式};
例:
select * from info where place_name like '_ei%';
语法:SELECT "栏位" FROM "表名" [WHERE "条件"] ORDER BY "栏位" [ASC, DESC];
#ASC 是按照升序进行排序的,是默认的排序方式。
#DESC 是按降序方式进行排序。
例:
select place_name,sales,date from info order by sales;
select place_name,sales,date from info order by sales asc;
select place_name,sales,date from info order by sales desc;
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);
avg() 返回指定列的平均值
count() 返回指定列中非 NULL 值的个数
min() 返回指定列的最小值
max() 返回指定列的最大值
sum(x) 返回指定列的所有值之和
#count(*)包括了所有的列的行数,在统计结果的时候,不会忽略值为NULL
#count(列名)只包括列名那一列的行数,在统计结果的时候,会忽略列值为NULL的行
例:
select avg(sales) from info;
select count(place_name) from info;
select count(distinct place_name) from info;
select max(sales) from info;
select min(sales) from info;
select sum(sales) from info;
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
reverse(x) 将字符串 x 反转
select TRIM ([ [位置] [要移除的字符串] from ] 字符串);
#[位置]:的值可以为 LEADING (起头), TRAILING (结尾), BOTH (起头及结尾)。
#[要移除的字符串]:从字串的起头、结尾,或起头及结尾移除的字符串。缺省时为空格。
例:
select trim(leading '123' from '1234567');
select concat(region, place_name) from destination;
select region || ’ ’ || place_name from destination;
select region || ’ ’ || place_name from destination where place_name = ‘beijing’;
select substr(place_name,3) from destination where place_name = 'beijing';
select substr(place_name,2,4) from destination where place_name = 'beijing';
select region,length(place_name) from destination;
select replace(region,'China',' ') from destination;
select upper(region) from destination;
select lower(region) from destination;
select left(region,5) from destination;
select right(region,5) from destination;
select repeat(region,2) from destination;
select repeat(123,2);
space(x) 返回 x 个空格
strcmp(x,y) 比较 x 和 y,返回的值可以为-1,0,1
reverse(x) 将字符串 x 反转
语法:SELECT "栏位1", SUM("栏位2") FROM "表名" GROUP BY "栏位1";
例:
select place_name,sum(sales) from info group by place_name order by sum(sales);
语法:SELECT "栏位1", SUM("栏位2") FROM "表格名" GROUP BY "栏位1" HAVING (函数条件);
例:
select place_name,sum(sales) from info group by place_name having sum(sales) > 400;
语法:SELECT "表格別名"."栏位1" [AS] "栏位別名" FROM "表格名" [AS] "表格別名";
例:
select A.place_name "name",sum(A.sales) "sum_sales" from info A group by name;
语法:
#外查询
SELECT "栏位1" FROM "表格1" WHERE "栏位2" [比较运算符]
#内查询
(SELECT "栏位1" FROM "表格2" WHERE "条件");
#可以是符号的运算符,例如:=、>、<、>=、<= ;也可以是文字的运算符,例如 LIKE、IN、BETWEEN
例1:
select sum(sales) from info where place_name in (select place_name from destination where region = 'southwest');
#下面这个句子就是上面的简化版
select sum(sales) from info where place_name in('chengdu','kunming');
例2:
select sum(a.sales) from info a where a.place_name in(select place_name from destination b where b.place_name = a.place_name);
语法:SELECT "栏位1" FROM "表格1" WHERE EXISTS (SELECT * FROM "表格2" WHERE "条件");
例:
select sum(sales) from info where exists (select * from destination where region = 'southwest');
SELECT * FROM 表1 表1的别名 INNER JOIN 表2 表2的别名 on 表1别名.栏位 = 表2别名.栏位; #这里的栏位名称相同
例:
select * from destination a inner join info b on a.place_name = b.place_name;
SELECT * FROM 表1 表1的别名 LEFT JOIN 表2 表2的别名 on 表1别名.栏位 = 表2别名.栏位; #这里的栏位名称相同
例:
select * from destination a left join info b on a.place_name = b.place_name;
SELECT * FROM 表1 表1的别名 RIGHT JOIN 表2 表2的别名 on 表1别名.栏位 = 表2别名.栏位; #这里的栏位名称相同
例:
select * from destination a right join info b on a.place_name = b.place_name;
语法:CREATE VIEW "视图表名" AS "SELECT 语句";
例:
create view new_info as select a.region region,a.place_name place_name,b.sales sales from destination a inner join info b on a.place_name = b.place_name;
select * from new_info;
drop view new_info;
UNION :生成结果的资料值将没有重复,且按照字段的顺序进行排序
语法:[SELECT 语句 1] UNION [SELECT 语句 2];
例:
select place_name from destination union select place_name from info;
UNION ALL :将生成结果的资料值都列出来,无论有无重复
语法:[SELECT 语句 1] UNION ALL [SELECT 语句 2];
例:
select place_name from destination union all select place_name from info;
select a.place_name from destination a inner join info b on a.place_name = b.place_name;
select a.place_name from destination a inner join info b using(place_name);
select a.place_name from (select place_name from destination union all select place_name from info) a group by a.place_name having count(*) > 1;
select a.place_name from (select b.place_name from destination b inner join info c on b.place_name =c.place_name) a group by a.place_name;
select distinct a.place_name from destination a inner join info b using(place_name);
select distinct place_name from destination where (place_name) in (select place_name from info);
select distinct a.place_name from destination a left join info b using(place_name) where b.place_name is not null;
select distinct place_name from destination where (place_name) not in (select place_name from info);
select distinct a.place_name from destination a left join info b using(place_name) where b.place_name is null;
语法:
SELECT CASE ("栏位名")
WHEN "条件1" THEN "结果1"
WHEN "条件2" THEN "结果2"
...
[ELSE "结果N"]
END
FROM "表名";
# “条件” 可以是一个数值或是公式。 ELSE 子句则并不是必须的。
例如:
select place_name, case place_name
when ‘beijing’ then sales - 50
when ‘kunming’ then sales - 20
else sales
end
“new sales”,date
from info;
#“New Sales” 是用于 CASE 那个栏位的栏位名。
在排序前先准备下用来实验的表格
create database school;
use school;
create table class(name varchar(20),scores int(5));
insert into class values ('aa1',80);
insert into class values ('bb2',100);
insert into class values ('cc3',78);
insert into class values ('dd4',94);
insert into class values ('ee5',66);
insert into class values ('ff6',53);
insert into class values ('gg7',77);
select * from class;
select a1.name, a1.scores,count(a2.scores) rank from class a1,class a2 where a1.scores < a2.scores or (a1.scores = a2.scores and a1.name = a2.name) group by a1.name,a1.scores order by a1.scores desc;
#统计scores栏位的值是比自己本身的值小的以及scores栏位和name栏位都相同的数量,比如ff6为6+1=7
select scores middle from (select a1.name, a1.scores,count(a2.scores) rank from class a1,class a2 where a1.scores < a2.scores or (a1.scores = a2.scores and a1.name <= a2.name) group by a1.name,a1.scores order by a1.scores desc) a3 where a3.rank = (select (count(*)+1) div 2 from class);
#每个派生表必须有自己的别名,所以别名 A3 必须要有
#DIV 是在 MySQL 中算出商的方式
select A1.*,sum(A2.scores) sum_socores from class A1,class A2 where A1.scores < A2.scores or(A1.scores = A2.scores and A1.name = A2.name) group by A1.name order by A1.scores desc;
select A1.*,A1.scores/(select sum(scores) from class) per_sum from class A1,class A2 where A1.scores < A2.scores or (A1.scores = A2.scores and A1.name=A2.name) group by A1.name order by A1.scores desc;
#SELECT SUM(Sales) FROM Total_Sales 这一段子查询是用来算出总合
#总合算出后,我们就能够将每一行一一除以总合来求出每一行的总合百分比
select A1.name,A1.scores,sum(A2.scores),sum(A2.scores)/(select sum(scores) from class) per_sum from class A1,class A2 where A1.scores < A2.scores or (A1.scores = A2.scores and A1.name=A2.name) group by A1.name order by A1.scores desc;
select A1.name,A1.scores,sum(A2.scores),truncate(sum(A2.scores)/(select sum(scores) from class),2) ||'%' per_sum from class A1,class A2 where A1.scores < A2.scores or (A1.scores = A2.scores and A1.name=A2.name) group by A1.name order by A1.scores desc;
如果觉得SQL语句有点长,建议大家可以采用视图的方法
SELECT length(NULL), length(''), length('1');
#建表
create table test(test varchar(20));
insert into test values(' ');
insert into test values('123123');
insert into test values();
insert into test values('1111');
insert into test values('');
select * from test;
例:
select * from test where test is null;
select * from test where test is not null;
select * from test where test = '';
select * from test where test <> '';
select count(test) from test;
匹配模式 描述 实例
^ 匹配文本的开始字符 ‘^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 {模式};
例:我这里使用上面实验的库
use plane
select * from info where place_name regexp '^b';
select * from info where place_name regexp 'ei|un';
格式:
DELIMITER $$ #将语句的结束符号从分号;临时改为两个$$(可以是自定义)
CREATE PROCEDURE xxx() #创建存储过程,过程名为xxx,不带参数
BEGIN #过程体以关键字 BEGIN 开始
sql语句; #过程体语句
END $$ #过程体以关键字 END 结束
DELIMITER ; #将语句的结束符号恢复为分号
例:
delimiter < s p a n c l a s s = " t o k e n k e y w o r d " > c r e a t e < / s p a n > < s p a n c l a s s = " t o k e n k e y w o r d " > p r o c e d u r e < / s p a n > c h a i n f o < s p a n c l a s s = " t o k e n p u n c t u a t i o n " > ( < / s p a n > < s p a n c l a s s = " t o k e n p u n c t u a t i o n " > ) < / s p a n > < s p a n c l a s s = " t o k e n k e y w o r d " > b e g i n < / s p a n > < s p a n c l a s s = " t o k e n k e y w o r d " > s e l e c t < / s p a n > < s p a n c l a s s = " t o k e n o p e r a t o r " > ∗ < / s p a n > < s p a n c l a s s = " t o k e n k e y w o r d " > f r o m < / s p a n > i n f o < s p a n c l a s s = " t o k e n p u n c t u a t i o n " > ; < / s p a n > < s p a n c l a s s = " t o k e n k e y w o r d " > e n d < / s p a n > create procedure cha_info() begin select * from info; end <spanclass="tokenkeyword">create</span><spanclass="tokenkeyword">procedure</span>chainfo<spanclass="tokenpunctuation">(</span><spanclass="tokenpunctuation">)</span><spanclass="tokenkeyword">begin</span><spanclass="tokenkeyword">select</span><spanclass="tokenoperator">∗</span><spanclass="tokenkeyword">from</span>info<spanclass="tokenpunctuation">;</span><spanclass="tokenkeyword">end</span>
delimiter ;
CALL 过程名;
例:
call cha_info;
SHOW CREATE PROCEDURE [数据库.]存储过程名; #查看某个存储过程的具体信息
例:
show create procedure cha_info;
show procedure status like ‘%cha_info’\G
例如:
delimiter !!
create procedure test1(in inname char(20))
begin
select * from info where place_name = inname;
end !!
delimiter ;
call test1(‘chengdu’);
存储过程内容的修改方法是通过删除原有存储过程,之后再以相同的名称创建新的存储过程。
DROP PROCEDURE 过程名; #仅当存在时删除,如果指定的过程不存在,会产生一个错误
DROP PROCEDURE IF EXISTS 过程名; #所以可以使用if exists确定存在后删除,不存在则不执行删除。
例:
drop procedure if exists test1;
create table t (id int);
insert into t values(10);
delimiter $$
create procedure test2(in shu int)
begin
declare var int;
set var=shu*2;
if var>=10 then
update t set id=id+1;
else
update t set id=id-1;
end if;
end $$
delimiter ;
call test2(6);
delimiter $$
create procedure test3()
begin
declare var int;
set var=0;
while var<6 do
insert into t values(var);
set var=var+1;
end while;
end $$
delimiter ;
call test3;