我有以下查询,我从表中选择所有 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