有時候需我們要組合幾張表的數據,在存儲過程中,經過比較復雜的運算獲取結果直接輸出給調用方,比如符合條件的幾張表的某些字段的組合計算,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();
??部分是字符編碼問題...大家可以改下字符集(我這里就不再修改了。)