【第4节】索引、视图、触发器、储存过程、
一、索引
索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构。类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取即可。
MySQL中常见索引有:
- 普通索引
- 唯一索引
- 主键索引
- 组合索引
1、普通索引
普通索引仅有一个功能:加速查询
1
2
3
4
5
6
7
8
|
创建表 + 索引 create table in1( nid int not null auto_increment primary key, name varchar( 32 ) not null, email varchar( 64 ) not null, extra text, index ix_name (name) )engine = innodb default charset = utf8; |
1
2
|
创建索引 create index index_name on table_name(column_name) |
1
2
|
删除索引 drop index_name on table_name; |
1
2
|
查看索引 show index from table_name; |
注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。
1
|
create index ix_extra on in1(extra( 32 )); |
2、唯一索引
唯一索引有两个功能:加速查询 和 唯一约束(可含null)
1
2
3
4
5
6
7
8
|
创建表 + 唯一索引 create table in1( nid int not null auto_increment primary key, name varchar( 32 ) not null, email varchar( 64 ) not null, extra text, unique ix_name (name) )engine = innodb default charset = utf8; |
1
2
3
4
5
|
创建唯一索引 create unique index 索引名 on 表名(列名) 删除唯一索引 drop unique index 索引名 on 表名 |
3、主键索引
主键有两个功能:加速查询 和 唯一约束(不可含null)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
创建表 + 创建主键 create table in1( nid int not null auto_increment primary key, name varchar( 32 ) not null, email varchar( 64 ) not null, extra text, index ix_name (name) )engine = innodb default charset = utf8; OR create table in1( nid int not null auto_increment, name varchar( 32 ) not null, email varchar( 64 ) not null, extra text, primary key(ni1), index ix_name (name) )engine = innodb default charset = utf8; 创建主键 alter table 表名 add primary key(列名); 删除主键 alter table 表名 drop primary key; alter table 表名 modify 列名 int , drop primary key; |
4、组合索引
组合索引是将n个列组合成一个索引
其应用场景为:频繁的同时使用n列来进行查询,如:where n1 = 'xyp' and n2 = 666。
1
2
3
4
5
6
7
8
9
10
11
|
创建表 create table in3( nid int not null auto_increment primary key, name varchar( 32 ) not null, email varchar( 64 ) not null, extra text )engine = innodb default charset = utf8; 创建组合索引 create index ix_name_email on in3(name,email); |
如上创建组合索引之后,查询:
- name and email -- 使用索引
- name -- 使用索引
- email -- 不使用索引
注意:对于同时搜索n个条件时,组合索引的性能好于多个单一索引合并。
5、其它注意事项
1
2
3
4
5
6
7
8
9
|
- 避免使用select * - count( 1 )或count(列) 代替 count( * ) - 创建表时尽量时 char 代替 varchar - 表的字段顺序固定长度的字段优先 - 组合索引代替多个单列索引(经常使用多个条件查询时) - 尽量使用短索引 - 使用连接(JOIN)来代替子查询(Sub - Queries) - 连表时注意条件类型需一致 - 索引散列值(重复少)不适合建索引,例:性别不适合 |
6、下列不走索引
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
- like '%xx' select * from tb1 where name like '%cn' ; - 使用函数 select * from tb1 where reverse(name) = 'wupeiqi' ; - or select * from tb1 where nid = 1 or email = 'seven@live.com' ; 特别的:当 or 条件中有未建立索引的列才失效,以下会走索引 select * from tb1 where nid = 1 or name = 'seven' ; select * from tb1 where nid = 1 or email = 'seven@live.com' and name = 'alex' - 类型不一致 如果列是字符串类型,传入条件是必须用引号引起来,不然... select * from tb1 where name = 999 ; - ! = select * from tb1 where name ! = 'alex' 特别的:如果是主键,则还是会走索引 select * from tb1 where nid ! = 123 - > select * from tb1 where name > 'alex' 特别的:如果是主键或索引是整数类型,则还是会走索引 select * from tb1 where nid > 123 select * from tb1 where num > 123 - order by select email from tb1 order by name desc; 当根据索引排序时候,选择的映射如果不是索引,则不走索引 特别的:如果对主键排序,则还是走索引: select * from tb1 order by nid desc; - 组合索引最左前缀 如果组合索引为:(name,email) name and email - - 使用索引 name - - 使用索引 email - - 不使用索引 |
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
二、视图
视图是一个虚拟表(非真实存在),其本质是【根据SQL语句获取动态的数据集,并为其命名】,用户使用时只需使用【名称】即可获取结果集,并可以将其当作表来使用。
临时表搜索
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
SELECT * FROM ( SELECT nid, NAME FROM tb1 WHERE nid > 2 ) AS A WHERE A. NAME > 'xyp' ; |
1、创建视图
1
2
3
4
5
6
7
8
|
- - 格式:CREATE VIEW 视图名称 AS SQL语句 CREATE VIEW v1 AS SELET nid, name FROM A WHERE nid > 4 |
2、删除视图
1
2
3
|
- - 格式:DROP VIEW 视图名称 DROP VIEW v1 |
3、修改视图
1
2
3
4
5
6
7
8
9
10
11
12
|
- - 格式:ALTER VIEW 视图名称 AS SQL语句 ALTER VIEW v1 AS SELET A.nid, B. NAME FROM A LEFT JOIN B ON A. id = B.nid LEFT JOIN C ON A. id = C.nid WHERE A. id > 2 AND C.nid < 5 |
4、使用视图
使用视图时,将其当作表进行操作即可,由于视图是虚拟表,所以无法使用其对真实表进行创建、更新和删除操作,仅能做查询用。
1
|
select * from v1 |
三、触发器
对某个表进行【增/删/改】操作的前后如果希望触发某个特定的行为时,可以使用触发器,触发器用于定制用户对表的行进行【增/删/改】前后的行为。
1、创建基本语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# 插入前 CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW BEGIN ... END # 插入后 CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW BEGIN ... END # 删除前 CREATE TRIGGER tri_before_delete_tb1 BEFORE DELETE ON tb1 FOR EACH ROW BEGIN ... END # 删除后 CREATE TRIGGER tri_after_delete_tb1 AFTER DELETE ON tb1 FOR EACH ROW BEGIN ... END # 更新前 CREATE TRIGGER tri_before_update_tb1 BEFORE UPDATE ON tb1 FOR EACH ROW BEGIN ... END # 更新后 CREATE TRIGGER tri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW BEGIN ... END |
插入前触发器
1
2
3
4
5
6
7
8
9
10
11
|
delimiter / / #修改sql默认以 ; 结束语句改为 // 结束语句 CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW #TRIGGER触发器,tri_before_insert_tb1触发器名,EACH ROW每行 BEGIN #begin内是触发触发器后执行的代码 IF NEW. NAME = = 'xyp' THEN INSERT INTO tb2 (NAME) VALUES ( 'aa' ) END END / / delimiter ; #再次修改会默认sql默认以 ; 结束 |
1
2
3
4
5
6
7
8
9
10
11
|
delimiter / / CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW BEGIN IF NEW. NAME = = 'xyp' THEN INSERT INTO tb2 (NAME) VALUES ( 'aa' ) END END / / delimiter ; |
插入后触发器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
delimiter / / CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW BEGIN IF NEW. num = 666 THEN INSERT INTO tb2 (NAME) VALUES ( '666' ), ( '666' ) ; ELSEIF NEW. num = 555 THEN INSERT INTO tb2 (NAME) VALUES ( '555' ), ( '555' ) ; END IF; END / / delimiter ; |
特别的:NEW表示即将插入的数据行,OLD表示即将删除的数据行。
2、删除触发器
1
|
DROP TRIGGER tri_after_insert_tb1; |
3、使用触发器
触发器无法由用户直接调用,而知由于对表的【增/删/改】操作被动引发的。
1
|
insert into tb1(num) values( 666 ) |
四、存储过程
存储过程是一个SQL语句集合,保存在MySQL上的一个别名。当主动去调用存储过程别名时,其中内部的SQL语句集合会按照逻辑执行。
1、创建存储过程
无参数存储过程
1
2
3
4
5
6
7
8
9
10
|
- - 创建存储过程 create procedure p1() BEGIN select * from student; INSERT into teacher(tname) values( "ct" ); END - - 执行存储过程 call p1() #sql中调用 cursor.callproc( 'p1' ) #pymysql中调用 |
对于存储过程,可以接收参数,其参数有三类:
- in 仅用于传入参数用
- out 仅用于返回值用
- inout 既可以传入又可以当作返回值
有参数的存储过程
1.1 参数in
1
2
3
4
5
6
7
8
9
10
11
12
13
|
- - 传参数 in delimiter / / create procedure p2( in n1 int , in n2 int ) BEGIN select * from student where sid > n1; END / / delimiter ; call p2( 12 , 2 ) # 12,2赋值给n1,n2传入存储过程中,用于sql语句的使用 cursor.callproc( 'p2' ,( 12 , 2 )) |
1.2 参数out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
- - 参数out delimiter / / create procedure p3( in n1 int , out n2 int ) BEGIN set n2 = 123123 ; select * from student where sid > n1; END / / delimiter ; set @v1 = 10 ; # 设置变量@V1 = 10,将10赋值给参数n2(out n2 int) call p3( 12 ,@v1) # 调用存储过程,查看执行的p3结果 select @v1; # 查看@v1的结果,因为上一步执行存储过程时n2的值已经被改变为123123 - - pycharm中调用 cursor.callproc( 'p3' ,( 12 , 2 )) #执行存储过程 r1 = cursor.fetchall() print (r1) # 拿到的是执行存储过程p3的结果 # 获取执行完存储的参数 cursor.execute( 'select @_p3_0,@_p3_1' ) @_p3_0赋值为 12 即n1,@_p3_1为 2 即n2 r2 = cursor.fetchall() print (r2) # 拿到的是存储过程p3的n2值 (12,123123) |
参数inout具备in和out都有的功能,不举例进行模拟。
1.3 游标
# 创建A,B表 把A表数据插入B表 create table A( id int, num int )engine=innodb default charset=utf8; create table B( id int not null auto_increment primary key, num int )engine=innodb default charset=utf8; insert into A(id,num) values(1,100),(2,200),(3,300); # 创建游标 delimiter // create procedure p9() begin declare row_id int; declare row_num int; declare done INT DEFAULT FALSE; declare temp int; declare my_cursor CURSOR FOR select id,num from A; declare CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; open my_cursor; xxoo: LOOP fetch my_cursor into row_id,row_num; if done then leave xxoo; END IF; set temp = row_id + row_num; insert into B(num) values(temp); end loop xxoo; close my_cursor; end // delimiter ; #执行 检查 call p9(); select * from B;
2、删除存储过程
1
|
drop procedure proc_name; |
3、执行存储过程
执行存储过程
1
2
3
4
5
6
7
8
9
10
|
- - 无参数 call proc_name() - - 有参数,全 in call proc_name( 1 , 2 ) - - 有参数,有 in ,out,inout set @t1 = 0 ; set @t2 = 3 ; call proc_name( 1 , 2 ,@t1,@t2) |
pymysql执行存储过程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123' , db = 't1' ) cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) # 执行存储过程 cursor.callproc( 'p1' , args = ( 1 , 22 , 3 , 4 )) # 获取执行完存储的参数 cursor.execute( "select @_p1_0,@_p1_1,@_p1_2,@_p1_3" ) result = cursor.fetchall() conn.commit() cursor.close() conn.close() print (result) |
五、函数
函数内不能写sql语句,会报错
MySQL中提供了许多内置函数,例如:
部分内置函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
CHAR_LENGTH( str ) 返回值为字符串 str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。 对于一个包含五个二字节字符集, LENGTH()返回值为 10 , 而CHAR_LENGTH()的返回值为 5 。 CONCAT(str1,str2,...) 字符串拼接 如有任何一个参数为NULL ,则返回值为 NULL。 CONCAT_WS(separator,str1,str2,...) 字符串拼接(自定义连接符) CONCAT_WS()不会忽略任何空字符串。 (然而会忽略所有的 NULL)。 CONV(N,from_base,to_base) 进制转换 例如: SELECT CONV( 'a' , 16 , 2 ); 表示将 a 由 16 进制转换为 2 进制字符串表示 FORMAT (X,D) 将数字X 的格式写为 '#,###,###.##' ,以四舍五入的方式保留小数点后 D 位, 并将结果以字符串的形式返回。若 D 为 0 , 则返回结果不带有小数点,或不含小数部分。 例如: SELECT FORMAT ( 12332.1 , 4 ); 结果为: '12,332.1000' INSERT( str ,pos, len ,newstr) 在 str 的指定位置插入字符串 pos:要替换位置其实位置 len :替换的长度 newstr:新字符串 特别的: 如果pos超过原字符串长度,则返回原字符串 如果 len 超过原字符串长度,则由新字符串完全替换 INSTR( str ,substr) 返回字符串 str 中子字符串的第一个出现位置。 LEFT( str , len ) 返回字符串 str 从开始的 len 位置的子序列字符。 LOWER( str ) 变小写 UPPER( str ) 变大写 LTRIM( str ) 返回字符串 str ,其引导空格字符被删除。 RTRIM( str ) 返回字符串 str ,结尾空格字符被删去。 SUBSTRING( str ,pos, len ) 获取字符串子序列 LOCATE(substr, str ,pos) 获取子序列索引位置 REPEAT( str ,count) 返回一个由重复的字符串 str 组成的字符串,字符串 str 的数目等于count 。 若 count < = 0 ,则返回一个空字符串。 若 str 或 count 为 NULL,则返回 NULL 。 REPLACE( str ,from_str,to_str) 返回字符串 str 以及所有被字符串to_str替代的字符串from_str 。 REVERSE( str ) 返回字符串 str ,顺序和字符顺序相反。 RIGHT( str , len ) 从字符串 str 开始,返回从后边开始 len 个字符组成的子序列 SPACE(N) 返回一个由N空格组成的字符串。 SUBSTRING( str ,pos) , SUBSTRING( str FROM pos) SUBSTRING( str ,pos, len ) , SUBSTRING( str FROM pos FOR len ) 不带有 len 参数的格式从字符串 str 返回一个子字符串,起始于位置 pos。带有 len 参数的格式从字符串 str 返回一个长度同 len 字符相同的子字符串,起始于位置 pos。 使用 FROM的格式为标准 SQL 语法。也可能对pos使用一个负值。假若这样,则子字符串的位置起始于字符串结尾的pos 字符,而不是字符串的开头位置。在以下格式的函数中可以对pos 使用一个负值。 mysql> SELECT SUBSTRING( 'Quadratically' , 5 ); - > 'ratically' mysql> SELECT SUBSTRING( 'foobarbar' FROM 4 ); - > 'barbar' mysql> SELECT SUBSTRING( 'Quadratically' , 5 , 6 ); - > 'ratica' mysql> SELECT SUBSTRING( 'Sakila' , - 3 ); - > 'ila' mysql> SELECT SUBSTRING( 'Sakila' , - 5 , 3 ); - > 'aki' mysql> SELECT SUBSTRING( 'Sakila' FROM - 4 FOR 2 ); - > 'ki' TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str ) TRIM(remstr FROM] str ) 返回字符串 str , 其中所有remstr 前缀和 / 或后缀都已被删除。若分类符BOTH、LEADIN或TRAILING中没有一个是给定的,则假设为BOTH 。 remstr 为可选项,在未指定情况下,可删除空格。 mysql> SELECT TRIM( ' bar ' ); - > 'bar' mysql> SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx' ); - > 'barxxx' mysql> SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx' ); - > 'bar' mysql> SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz' ); - > 'barx' |
1、显示时间月份
1
2
3
4
|
select DATE_FORMAT(ctime, "%Y-%m" ),count( 1 ) from blog group DATE_FORMAT(ctime, "%Y-%m" ) 2019 - 11 2 2019 - 10 2 |
2、自定义函数
1
2
3
4
5
6
7
8
9
10
11
12
13
|
delimiter \\ create function f1( #f1函数名 i1 int , #设置参数i1和i2的类型为int i2 int ) returns int #设置returns返回值类型为int BEGIN #begin内为执行的代码 declare num int ; #声明变量 set num = i1 + i2; #函数的执行 return (num); #返回函数的执行结果 END \\ delimiter ; SELECT f1( 1 , 99 ); #执行函数 |
1
2
3
4
5
6
7
8
|
#执行函数 select f1( 1 , 99 ); + - - - - - - - - - - + | f1( 1 , 99 ) | + - - - - - - - - - - + | 100 | + - - - - - - - - - - + |
3、删除函数
1
|
drop function func_name; |
4、执行函数
1
2
3
4
5
6
7
8
|
# 获取返回值 declare @i VARCHAR( 32 ); select UPPER( 'alex' ) into @i; SELECT @i; # 在查询中使用 select f1( 11 ,nid) ,name from tb2; |
六、事务
事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性。
支持事务的存储过程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
delimiter \\ create PROCEDURE p1( OUT p_return_code tinyint ) BEGIN DECLARE exit handler for sqlexception BEGIN - - ERROR set p_return_code = 1 ; rollback; END; DECLARE exit handler for sqlwarning BEGIN - - WARNING set p_return_code = 2 ; rollback; END; START TRANSACTION; DELETE from tb1; insert into tb2(name)values( 'seven' ); COMMIT; - - SUCCESS set p_return_code = 0 ; END\\ delimiter ; |
1
2
3
|
set @i = 0 ; call p1(@i); select @i; |
a.数据库开启事务命令
1
2
3
4
|
start transaction 开启事务 Rollback 回滚事务,即撤销指定的sql语句(只能回退insert delete update语句),回滚到上一次commit的位置 Commit 提交事务,提交未存储的事务 savepoint 保留点 ,事务处理中设置的临时占位符 你可以对它发布回退(与整个事务回退不同) |
b.数据库事务操作演示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
create table account( id int , name varchar( 32 ), balance double); insert into account values( 1 , "alex" , 8000 ); insert into account values( 2 , "egon" , 2000 ); #方式一: 更改数据后回滚,数据回到原来 select * from account; + - - - - - - + - - - - - - + - - - - - - - - - + | id | name | balance | + - - - - - - + - - - - - - + - - - - - - - - - + | 1 | alex | 8000 | | 2 | egon | 2000 | + - - - - - - + - - - - - - + - - - - - - - - - + start transaction; #开启事务后,更改数据发现数据变化 update account set balance = balance - 1000 where id = 1 ; #alex减去1000 select * from account; + - - - - - - + - - - - - - + - - - - - - - - - + | id | name | balance | + - - - - - - + - - - - - - + - - - - - - - - - + | 1 | alex | 7000 | | 2 | egon | 2000 | + - - - - - - + - - - - - - + - - - - - - - - - + rollback; #回滚后,发现数据回到原来 select * from account; + - - - - - - + - - - - - - + - - - - - - - - - + | id | name | balance | + - - - - - - + - - - - - - + - - - - - - - - - + | 1 | alex | 8000 | | 1 | egon | 2000 | + - - - - - - + - - - - - - + - - - - - - - - - + #方式二: 更改数据后提交 select * from account; + - - - - - - + - - - - - - + - - - - - - - - - + | id | name | balance | + - - - - - - + - - - - - - + - - - - - - - - - + | 1 | alex | 8000 | | 2 | egon | 2000 | + - - - - - - + - - - - - - + - - - - - - - - - + update account set balance = balance - 1000 where id = 1 ; pdate account set balance = balance + 1000 where id = 2 ; Commit; select * from account; + - - - - - - + - - - - - - + - - - - - - - - - + | id | name | balance | + - - - - - - + - - - - - - + - - - - - - - - - + | 1 | alex | 7000 | | 2 | egon | 3000 | + - - - - - - + - - - - - - + - - - - - - - - - + |
c. python中调用数据库启动事务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import pymysql #添加数据 conn = pymysql.connect(host = '10.37.129.3' , port = 3306 , user = 'egon' , passwd = '123456' , db = 'wuSir' ,charset = "utf8" ) cursor = conn.cursor() try : insertSQL0 = "INSERT INTO account (name,balance) VALUES ('oldboy',4000)" insertSQL1 = "UPDATE account set balance=balance-1000 WHERE id=1" insertSQL2 = "UPDATE account set balance=balance+1000 WHERE id=2" cursor = conn.cursor() cursor.execute(insertSQL0) conn.commit() #主动触发Exception,事务回滚,回滚到上面conn.commit() cursor.execute(insertSQL1) raise Exception cursor.execute(insertSQL2) cursor.close() conn.commit() except Exception as e: conn.rollback() conn.commit() cursor.close() conn.close() |
七、分页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
a. select * from userinfo3 limit 20 , 10 ; #但是到limit 200000,10会很慢 b. - 不让看 - 索引表中扫: #提高一些效率,但不是最优结果 select * from userinfo3 where id in (select id from userinfo3 limit 200000 , 10 ) - 方案: 记录当前页最大或最小 ID 1. 页面只有上一页,下一页 # max_id # min_id 下一页: select * from userinfo3 where id > max_id limit 10 ; 上一页: select * from userinfo3 where id < min_id order by id desc limit 10 ; 2. 上一页 192 193 [ 196 ] 197 198 199 下一页 #跳页,从196跳到199 select * from userinfo3 where id in ( select id from (select id from userinfo3 where id > max_id limit 30 ) as N order by N. id desc limit 10 )<br> # 注:id可能不连续,所以无法直接用id范围进行查找 |
八、其他
1、条件语句
if条件语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
delimiter \\ CREATE PROCEDURE proc_if () BEGIN declare i int default 0 ; if i = 1 THEN SELECT 1 ; ELSEIF i = 2 THEN SELECT 2 ; ELSE SELECT 7 ; END IF; END\\ delimiter ; |
2、循环语句
while循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
delimiter \\ CREATE PROCEDURE proc_while () BEGIN DECLARE num INT ; SET num = 0 ; WHILE num < 10 DO SELECT num ; SET num = num + 1 ; END WHILE ; END\\ delimiter ; |
repeat循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
delimiter \\ CREATE PROCEDURE proc_repeat () BEGIN DECLARE i INT ; SET i = 0 ; repeat select i; set i = i + 1 ; until i > = 5 end repeat; END\\ delimiter ; |
loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
BEGIN declare i int default 0 ; loop_label: loop set i = i + 1 ; if i< 8 then iterate loop_label; end if ; if i> = 10 then leave loop_label; end if ; select i; end loop loop_label; END |
3、动态执行SQL语句
动态执行SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
delimiter / / create procedure p7( in tpl varchar( 255 ), in arg int ) begin 1. 预检测某个东西 SQL语句合法性 2. SQL = 字符串格式化 (tpl + arg) 3. 执行SQL语句 set @xo = arg; PREPARE xxx FROM 'select * from student where sid > ?' ; # ? 为占位符。此处为@xo EXECUTE xxx USING @xo; DEALLOCATE prepare prod; # 执行已经格式化完成的sql语句 end / / delimter ; call p7( "select * from tb where id > ?" , 9 ) # call p7("select * from tb where id > 9") = = = > delimiter \\ CREATE PROCEDURE p8 ( in nid int ) BEGIN set @nid = nid; PREPARE prod FROM 'select * from student where sid > ?' ; EXECUTE prod USING @nid; DEALLOCATE prepare prod; END\\ delimiter ; |