MySQL 5 6 MRR 的儲存過程完美詮釋

2022-09-17 12:18:08 字數 2805 閱讀 5892

mysql 5.6 即將發布, 5.6對優化器方面做了諸多優化。 我這次主要解釋mrr(multi-range-read)。

我用儲存過程解釋了這一過程的改變。大家細心體會去吧。

我們針對語句:

select log_time from person where nick_name = 'lucy';

表結構為:

create table `person` (

`id` int(10) unsigned not null auto_increment,

`nick_name` varchar(40) not null,

`log_time` timestamp not null default current_timestamp,

primary key (`id`),

key `idx_nick_name` (`nick_name`)

) engine=innodb auto_increment=5 default charset=latin1

首先是mysql 5.5.

delimiter $$

use `ytt`$$

drop procedure if exists `sp_range_scan5_5`$$

create definer=`admin`@`%` procedure `sp_range_scan5_5`()

begin

-- sample sql statement is below.

-- select log_time from person where nick_name = 'lucy';

declare i int unsigned default 0;

declare cnt int unsigned default 0;

set @result = '';

select count(1) into cnt from person where nick_name = 'lucy';

loop1:while i < cnt

doset @stmt = concat('select id into @v_id from person where nick_name = ''lucy'' order by nick_name asc limit ',i,',1');

prepare s1 from @stmt;

execute s1;

set @result = concat(@result,'select log_time from person where id = @v_id');

set @result = concat(@result,' union all ');

set i = i + 1;

end while loop1;

set @result = substr(@result,1,char_length(@result)-char_length(' union all '));

prepare s1 from @result;

execute s1;

drop prepare s1;

set @result = null;

end$$

delimiter ;

下來是mysql 5.6.

delimiter $$

use `ytt`$$

drop procedure if exists `sp_range_scan5_6`$$

create definer=`admin`@`%` procedure `sp_range_scan5_6`()

begin

-- sample sql statement is below.

-- select log_time from person where nick_name = 'lucy';

declare i int unsigned default 0;

declare cnt int unsigned default 0;

declare ids text;

set ids = '';

select count(1) into cnt from person where nick_name = 'lucy';

loop1:while i < cnt

doset @stmt = concat('select id into @v_id from person where nick_name = ''lucy''

order by nick_name asc limit ',i,',1');

prepare s1 from @stmt;

execute s1;

set ids = concat(ids,@v_id,',');

set i = i + 1;

end while loop1;

set ids = concat('(',substr(ids,1,char_length(ids)-1),')');

set @result = concat('select log_time from person where id in',ids);

prepare s1 from @result;

execute s1;

drop prepare s1;

set @result = null;

end$$

delimiter ;

原!mysql5 6 儲存過程 批量建表

由於業務需求,需要按天分表,因此寫了個儲存過程,根據時間生成表。根據createtime 的時間,以及 while迴圈的變數設定範圍,生成該指定日期及之後的多張表。begin declare i int 11 declare createtime varchar 32 set i 0 set cre...

mysql儲存過程 MySQL儲存過程

在本節中,您將逐步學習如何在mysql中編寫和開發儲存過程。首先,我們向您介紹儲存過程的概念,並討論何時使用它。然後,展示如何使用過程 的基本元素,如建立儲存過程的語句,if else,case,loop,儲存過程的引數。下面每個教程都包含了易於理解的示例和詳細的說明。如果您瀏覽並學習所有教程,您可...

mysql 儲存過程 mysql 儲存過程

建立 為建立儲存過程的結束標誌,使用delimiter 可更改標誌 格式create procedure begin sqlend create procedure myprocedure in param integer begin select from tb role where tb rol...