1. 程式人生 > 資料庫 >mysql - 臨時表暫存資料

mysql - 臨時表暫存資料

1. 使用臨時表暫存資料,然後拼接得到的所有結果(postgresql)

drop  table  IF EXISTS temp_stock_beginning;
drop  table  IF EXISTS temp_stock_move_in;
drop  table  IF EXISTS temp_stock_move_out;

create temp table temp_stock_beginning(product_id int, location_id int,qty int,res_company_id int);
create temp table temp_stock_move_in(product_id int, location_id int,qty int,res_company_id int);
create temp table temp_stock_move_out(product_id int, location_id int,qty int,res_company_id int);

insert into temp_stock_beginning(product_id,location_id,qty,res_company_id int) 
        select product_id,stock_location_id as location_id,qty,res_company_id
        from company_stock_remain 
        where data_date='{}';
        
insert into temp_stock_move_in(product_id,location_id,qty,res_company_id) 
        select product_id,b.origin_id as location_id,-1*qty,res_company_id
        from company_stock_move_detail a 
        inner join stock_location b on a.from_stock_location_id=b.id
        where b.usage='internal' and a.data_date='{}';
        
insert into temp_stock_move_out(product_id,location_id,qty,res_company_id)
        select product_id,b.origin_id as location_id,qty ,res_company_id
        from company_stock_move_detail a 
        inner join stock_location b on a.to_stock_location_id=b.id
        where b.usage='internal' and a.data_date='{}';
        
insert into company_stock_remain(product_id,stock_location_id,qty,data_date,res_company_id)
        select product_id,location_id,sum(qty),'{}',res_company_id from 
                        (select product_id,location_id,qty,res_company_id from temp_stock_beginning 
                        union all 
                        select product_id,location_id,qty,res_company_id from temp_stock_move_in
                        union all 
                        select product_id,location_id,qty,res_company_id from temp_stock_move_out
                        ) as a
                        where qty != 0
                        group by product_id,location_id