mysql 儲存過程 使用記憶體表代替游標

2021-10-19 05:21:34 字數 2179 閱讀 6953

一、mysql游標的概念

1、游標介紹

mysql的游標(cursor)是乙個重要的概念,通過查詢資料與自己的理解,主要得出以下幾點關於自己的理解。

有資料緩衝的思想:游標的設計是一種資料緩衝區的思想,用來存放sql語句執行的結果。 先有資料基礎:游標是在先從資料表中檢索出資料之後才能繼續靈活操作的技術。 類似於指標:游標類似於指向資料結構堆疊中的指標,用來pop出所指向的資料,並且只能每次取乙個。

游標的缺點是針對有點而言的,也就是只能一行一行操作,在資料量大的情況下,是不適用的,速度過慢。這裡有個比喻就是:當你去atm存錢是希望一次性存完呢,還是100一張一張的存,這裡的100一張一張存就是游標針對行的操作。 資料庫大部分是面對集合的,業務會比較複雜,而游標使用會有死鎖,影響其他的業務操作,不可取。 當資料量大時,使用游標會造成記憶體不足現象。那這個時候我們可以記憶體表來解決這個問題,還是置接上sql把,也是第一次寫,希望大家不要噴

begin

– 定義變數

declare order_count int; – 數量

declare area_intro char(50); – 區域

declare count_time datetime;

declare maxid int default 0;

declare i int default 0;

– 先銷毀臨時表

drop table if exists count_order_statistics_temp;

– 建立臨時表

create temporary table count_order_statistics_temp(

idint(11) not null auto_increment,

order_countint(11) default 『0』 comment 『訂單數量』,

area_introchar(50) default null comment 『區域』,

count_timedatetime default null comment 『統計時間』,

primary key (`id`)  

)engine=myisam default charset=utf8;

insert into count_order_statistics_temp(order_count,area_intro,count_time)

select

ifnull(count(1),『0』)order_count,m.area_intro,date_format(now(),』%y-%m-%d』)count_time from user_judge j

left join merchant m on m.id=j.merchant_id

where j.state<>8 and to_days(now()) = to_days(j.begin_time) group by m.area_intro;

– 查詢臨時表最大的id

select max(id) into maxid from count_order_statistics_temp;

select min(id) into i from count_order_statistics_temp;

– 開始迴圈

while i <= maxid do

select order_count, area_intro,date_format(now(),』%y-%m-%d』) into order_count, area_intro,count_time from count_order_statistics_temp where id = i;

set i = i + 1;

end while;

end$$

delimiter ;

到這裡儲存過程就寫完成啦,然後執行,如果不報錯的話就可以呼叫儲存過程啦

然後呼叫儲存過程 使用 call 儲存過程名稱,呼叫成功後,查詢剛才統計的資料使用 select 欄位名稱 from 臨時表名稱 。有**不對的地方還希望各位能幫忙指出,謝謝!

mysql儲存過程表 mysql儲存過程和表命令

show procedure status 2.顯示某個儲存過程的詳細資訊 sp為儲存過程名稱 show create procedure sp 3.顯示當前庫中所有表 show tables 4.顯示某個表的建表語句 test為表名 show create table test 5.刪除儲存過程 ...

Mysql儲存過程使用

案例 create procedure sp insert graduate certificate in psid varchar 200 in certificateid int 32 in number varchar 50 in userid int 32 in starttime date...

儲存過程 MySQL儲存過程的使用總結

案例所涉及到的表如下 create table t goods g id varchar 20 not null comment 商品編號 g name varchar 30 default null comment 商品名稱 g price float default null comment 商...