mysql游標中使用臨時表


有時候需我們要組合幾張表的數據,在存儲過程中,經過比較復雜的運算獲取結果直接輸出給調用方,比如符合條件的幾張表的某些字段的組合計算,mysql臨時表可以解決這個問題.

所謂臨時表:只有在當前連接情況下, TEMPORARY 表才是可見的。當連接關閉時, TEMPORARY 表被自動取消。必須擁有 create temporary table 權限,才能創建臨時表。可以通過指定 engine = memory; 來指定創建內存臨時表。

drop table if exists  pre_person;
create table `person` (
  `id` int(11)primary key NOT NULL DEFAULT '0',
  `age` int(11) DEFAULT NULL,
  `name` varchar(25) not null
) engine=innodb default charset=utf8;
insert into person values(1,1,'張三'),(2,2,'李四'),(3,3,'王五'),(4,4,'趙六'),(5,5,'許仙');

臨時表支持主鍵、索引指定。在連接非臨時表查詢可以利用指定主鍵或索引來提升性能。比如這里我用存儲過程語句及游標和臨時表綜合實例:

drop procedure if exists sp_test; -- 判斷存儲過程函數是否存在如果是刪除
delimiter ;;
create procedure  sp_test()  
begin  
         create temporary table if not exists tmp   -- 如果表已存在,則使用關鍵詞 if not exists 可以防止發生錯誤
         (  
           id int(11) ,  
           name varchar(10),  
           age int(3)
         ) engine = memory;  
         begin  
        declare ids int; -- 接受查詢變量
        declare names varchar(10); -- 接受查詢變量
        declare done int default false; -- 跳出標識
        declare ages int(3); -- 接受查詢變量
        declare cur cursor for select id from person; -- 聲明游標
        declare continue handler for not FOUND set done = true; -- 循環結束設置跳出標識
        open cur; -- 開始游標
        LOOP_LABLE:loop -- 循環
            FETCH cur INTO ids;
            select name into names from person where id=ids;
            select age into ages from person where id=ids;
            insert into tmp(id,name,age) value(ids,names,ages);
            if done THEN  -- 判斷是否繼續循環如果done等於true離開循環
                LEAVE LOOP_LABLE; -- 離開循環
            END IF;
            end LOOP; -- 結束循環
        CLOSE cur; -- 關閉游標
     select * from tmp; -- 查詢臨時表
         end;  
         truncate TABLE tmp;   -- 使用 truncate TABLE 的方式來提升性能
end;  
;;
delimiter ;;

然后執行存儲過程:

call sp_test();

??部分是字符編碼問題...大家可以改下字符集(我這里就不再修改了。)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM