如何将查询存储到变量中以便我可以使用它两次?

时间:2012-11-09 15:23:07

标签: mysql variables optimization select

我有以下查询,我从表中选择所有ID进行比较,以过滤一些ID作为'backblaze sales orders'。我注意到每次检查报告后,它会花费10秒钟的时间。如何将该表选择为可以比较事物的变量以提高效率,以便不反复查询表?

到目前为止,我已经使用了保罗答案中的temp_table,但它给出了一个错误,上面写着“无法重新开启临时表达。”

CREATE TEMPORARY TABLE if not exists TempTable (id varchar(36)); 
INSERT INTO TempTable (id)
SELECT
   id
FROM 
   reporting.backblaze_sales_orders;
SELECT
  2011 as year,
  so.technical_address_country,
  so.technical_address_state,
  /* ALL JOBs */
  COUNT(so.id) as all_sales,
  COUNT(mf.id) as all_jobs,
  SUM(so.total_value) as all_value,
    SUM(IF(so.check_if_new_customer=1,1,0)) as sales_order_new,
  SUM(IF(so.check_if_new_customer = 1,so.total_value,0)) as total_value_new,
    SUM(IF(so.check_if_new_customer=1 AND mf.id IS NOT NULL,1,0)) as jobs_new,
    SUM(IF(so.check_if_new_customer=0,1,0)) as sales_order_existing,
  SUM(IF(so.check_if_new_customer = 0,so.total_value,0)) as total_value_existing,
    SUM(IF(so.check_if_new_customer=0 AND mf.id IS NOT NULL,1,0)) as jobs_existing,
      /* ALL JOBs */
  COUNT(so.id) as all_sales_back_blaze,
  COUNT(mf.id) as all_jobs_back_blaze,
  SUM(so.total_value) as all_value,
    SUM(IF(so.check_if_new_customer=1 AND so.id not in (SELECT id from TempTable) ,1,0)) as sales_order_new_back_blaze,
  SUM(IF(so.check_if_new_customer = 1 AND so.id not in (SELECT id from TempTable),so.total_value,0)) as total_value_new_back_blaze,
    SUM(IF(so.check_if_new_customer=1 AND  mf.id IS NOT NULL AND so.id not in (SELECT id from TempTable),1,0)) as jobs_new_back_blaze,
    SUM(IF(so.check_if_new_customer=0 AND so.id not in (SELECT id from TempTable),1,0)) as sales_order_existing_back_blaze,
  SUM(IF(so.check_if_new_customer = 0 AND so.id not in (SELECT id from TempTable),so.total_value,0)) as total_value_existing_back_blaze,
    SUM(IF(so.check_if_new_customer=0 AND mf.id IS NOT NULL AND so.id not in (SELECT id from TempTable),1,0)) as jobs_existing_back_blaze
FROM 
  sugarcrm2.so_order so 
LEFT JOIN 
  sugarcrm2.mf_job mf on so.id = mf.sales_order_id 
WHERE 
  so.date_entered > "2010-10-30" AND so.date_entered >"2011-10-30" AND
    so.technical_address_country IS NOT NULL AND  
  so.technical_address_state IS NOT NULL AND 
  so.deleted = 0 AND 
  so.has_been_promoted = 1 
GROUP BY 
    YEAR(so.date_entered),
  so.technical_address_country, 
  so.technical_address_state
ORDER BY 
  so.technical_address_country, so.technical_address_state 

3 个答案:

答案 0 :(得分:2)

没有阅读所有代码,但听起来你需要一个临时表。这些可以这样使用:

CREATE TEMPORARY TABLE TempTable (id int, otherValue varchar(100)); 

INSERT INTO TempTable (id, otherValue)
SELECT
   id,
   someOtherValue
FROM ....

然后使用此表而不是您的查询。

答案 1 :(得分:1)

使用游标: http://www.brainbell.com/tutorials/MySQL/Working_With_Cursors.htm

DECLARE ordernumbers CURSOR
   FOR
   SELECT ordernum FROM orders;

这只是一个暗示! 我希望有人可以用它来给出完整的答案。

答案 2 :(得分:0)

答案是简单地加入该表并测试连接表的id是否为null。