从多个查询中插入新表

时间:2016-04-14 22:24:19

标签: mysql mysql-workbench

我有这些查询,我想将这些结果插入到一个临时表中。我怎么能这样做?

select date(max(created_date)) AS 'Last Shipped Date',
sum(item_count) AS 'Last Shipped Units'
from order 
where is_shipped = 1
AND date(shipped_date) = (select date(max(shipped_date)) from order); 

select 
count(distinct o.key) AS 'ACTIVE ',
count(od.ean) AS 'Active_ Units'
from order o 
left join order_details od on o.id = od. order_details
Where o.is_active = 1;

select count(distinct order_key) AS 'Total_Orders_Shipped_Yesterday',
sum(item_count) AS 'Total_units_Shipped_yesterday' 
from order
where datediff(curdate(), modified_date)=1
AND is_shipped =1;


select count(distinct liquidation_order_id) AS 'orders cancelled',
count(ean) AS 'Units cancelled'
from order_details
where datediff(curdate(), modified_date)=1
AND order_details_status_ =4;

1 个答案:

答案 0 :(得分:0)

可能有一种方法可以在一个查询中执行,但它会很复杂。通过与计算值的其他查询相结合,只需执行一系列UPDATE查询就可以更轻松地填充表中的相应列。

CREATE TEMPORARY TABLE tempTable (
    `Last Shipped Date` DATE,
    `Last Shipped Units` INT,
    Active INT,
    Active_Units INT,
    Total_Orders_Shipped_Yesterday INT,
    Total_units_Shipped_yesterday INT,
    `orders cancelled` INT,
    `Units cancelled` INT);

INSERT INTO tempTable (`Last Shipped Date`, `Last Shipped Units`)
select date(max(created_date)) AS 'Last Shipped Date',
sum(item_count) AS 'Last Shipped Units'
from order 
where is_shipped = 1
AND date(shipped_date) = (select date(max(shipped_date)) from order); 

UPDATE tempTable AS t
JOIN order o 
left join order_details od on o.id = od. order_details
SET t.Active = count(distinct o.key), t.Active_Units = count(od.ean)
Where o.is_active = 1;

UPDATE tempTable AS t
JOIN order
SET t.Total_Orders_Shipped_Yesterday = count(distinct order_key),
    t.Total_units_Shipped_yesterday = SUM(item_count)
where datediff(curdate(), modified_date)=1
    AND is_shipped =1;

UPDATE tempTable AS t
JOIN order_details
SET t.`orders cancelled` = count(distinct liquidation_order_id),
    t.`Units cancelled` = COUNT(ean)
where datediff(curdate(), modified_date)=1
    AND order_details_status_ =4;