論MySQL中如何代替Oracle中select into new_table from old_table


 v_receipt         warehouse_receipt%ROWTYPE;-- 這里創建表類型,v_receipt復刻了warehouse_receipt的類型(相當於擁有了所有相同的字段)

select * into v_receipt_detail from warehouse_receipt_detail d where d.receipt_detail_id = v_detailId;

**而在MySQL總無法用select into new_table from old_table這個語句**

但是MySQL中有temporary table這個臨時表

如何復刻另一張表呢,語句來了

create temporary table new_table (select * from old_table)

這樣就創建了一個新的臨時表

drop table if exists temp_table;
create temporary table temp_table(select * from test_table);
select name from temp_table where id=2; -- 這句話同樣能用

 

那么,為什么要用這種表變量和復刻的臨時表呢?

其實這種臨時表是動態的,在滿足某種篩選條件下,產生的篩選出的主表

test_table

delimiter $$
-- drop table if exists temp_table;
create procedure temp_test()
begin
drop table if exists temp_table;
create temporary table temp_table(select * from test_table);
-- set @name=temp_table.name;
select name from temp_table where id=2;
end$$
delimiter

測試 

call temp_test()

結果

name

------

nyu-ploy

另保留一段代碼

delimiter $$
drop procedure if exists test_at $$
create definer=root@localhost procedure test_at()
begin
declare i1 integer default 1;
set i1=i1+1;
set @i2=i2+1;
select i1,@i2;
end $$
delimiter;

 **但重點是在oracle 中,表類型可以直接引用字段,即

v_inventoryTotal warehouse_inventory_total%ROWTYPE

v_inventoryTotal.XXId可以直接用,特別是ROWTYPE的表只有一行時,此時引用字段就是一個值

但是對於臨時表 temp_table不可以直接 '.id'同時實質表也不可以

在MySQL中引用字段都要起別名 ,這和對象的道理一樣,所以想用其中的字段,只能這樣

 

delimiter $$
drop procedure if exists temp_test $$
create definer=root@localhost procedure temp_test()
begin
declare i1 integer default 1;
drop table if exists temp_table;
create temporary table temp_table(select * from test_table t where t.id=2);
select name into @temp_table_name from temp_table;
select @temp_table_name;
end $$
delimiter;

call temp_test ,就有一個值出來 即nyu-poly

如果這里where t.id>2,就會報錯:Result consisted of more than one row 即@temp_table_name不可以是多個值

 

 

 


免責聲明!

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



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