临时表而不是连接

时间:2012-09-24 04:53:39

标签: mysql sql join

以下查询按预期工作。 但是,选择数据的摘要表太大。查询需要花费很多时间。

SELECT s.date_time AS date_time,SUM(s.requests) AS sum_requests,SUM(s.impressions) AS sum_views,SUM(s.clicks) AS sum_clicks,SUM(s.conversions) AS sum_conversions,
SUM(s.total_revenue) AS sum_revenue,SUM(s.total_revenue)  AS sum_spend,
SUM(s.total_basket_value) AS sum_bv,SUM(s.total_num_items) AS sum_num_items,SUM(s.total_pubrevenue) AS sum_pubrevenue
FROM ox_data_summary_ad_hourly AS s 
INNER JOIN ox_banners AS d ON (d.bannerid=s.ad_id) 
INNER JOIN ox_campaigns AS m ON (m.campaignid=d.campaignid) 
INNER JOIN ox_clients AS a ON (a.clientid=m.clientid) 
LEFT JOIN ox_zones AS z ON (z.zoneid=s.zone_id) 
LEFT JOIN ox_affiliates AS p ON (p.affiliateid=z.affiliateid)
WHERE a.agencyid = 3 AND z.zone_type = 'application' AND z.delivery = 8 
AND s.date_time>='2012-07-01 00:00:00' AND s.date_time<='2012-07-01 23:59:59' 
GROUP BY date_time

我需要简化连接。有没有办法为所有连接创建临时表,然后将该表连接到基表。 这是我到目前为止所尝试过的。

drop table if exists test.helper;
create table test.helper 
select d.network_type , d.is_network, d.bannerid, p.agencyid, z.zone_type, z.delivery , z.zoneid
FROM ox_banners as d
INNER JOIN ox_campaigns AS m ON (m.campaignid=d.campaignid) 
INNER JOIN ox_clients AS a ON (a.clientid=m.clientid) 
left JOIN ox_agency as oa ON (oa.account_id = a.clientid)
left JOIN ox_affiliates AS p ON (p.agencyid = oa.agencyid)
left JOIN ox_zones AS z ON (z.affiliateid = p.affiliateid);

alter table test.helper add key(bannerid, zoneid);

但是当与原始表连接时,它不会返回正确的结果。

SELECT s.ad_id, s.date_time AS date_time,SUM(s.requests) AS sum_requests,SUM(s.impressions) AS sum_views,SUM(s.clicks) AS sum_clicks,SUM(s.conversions) AS sum_conversions,
SUM(s.total_revenue) AS sum_revenue,SUM(s.total_revenue)  AS sum_spend,
SUM(s.total_basket_value) AS sum_bv,SUM(s.total_num_items) AS sum_num_items,SUM(s.total_pubrevenue) AS sum_pubrevenue
FROM ox_data_summary_ad_hourly AS s 
inner JOIN test.helper  AS d ON (d.bannerid=s.ad_id )
where d.agencyid = 3 AND d.zone_type = 'application' AND d.delivery = 8  and s.date_time>='2012-07-01 00:00:00' AND s.date_time<='2012-07-01 23:59:59' 
GROUP BY date_time

1 个答案:

答案 0 :(得分:1)

首先,我将LEFT JOIN替换为INNER JOINS。由于ox_zones上有WHERE子句,LEFT JOIN创建的空值无论如何都会丢失。外连接显然很昂贵,应尽可能避免使用。

在合理的现代RDBMS上,通过创建临时表来对查询规划器进行二次猜测通常会适得其反。您的所有加入条件是否已编入索引?您的WHERE子句中引用的列是否已编入索引?