0

我有以下查询,我从表中选择所有 id 进行比较,以将某些 id 过滤为“backblaze 销售订单”。我注意到每次检查报告后,它会增加 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 
4

3 回答 3

2

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

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

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

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

于 2012-11-09T15:24:47.637 回答
1

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

DECLARE ordernumbers CURSOR
   FOR
   SELECT ordernum FROM orders;

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

于 2012-11-09T15:26:45.623 回答
0

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

于 2012-11-09T19:20:49.353 回答