我有一個報表的SQL查詢,它包括幾個子查詢。它運行速度很慢。我嘗試了幾種方法(如使用連接而不是子查詢,添加幾個索引)。但他們都沒有工作。以下是查詢:TSQL查詢運行緩慢,如何加速?
declare @time_from datetime
declare @time_to datetime
set @time_from ='2012-01-01'
set @time_to = '2014-01-01'
select a.a_id, c.c_id, c.c_chat_line_id, a.a_first_name, a.a_last_name
,(select isnull(SUM(ac.ac_amount),0) from t_actress_credit ac join t_order o on o.o_id = ac.order_id where o.o_status = 1 and ac.actress_id = a.a_id and ac.ac_time>[email protected]_from and ac.ac_time<[email protected]_to) as credit
,(select isnull(SUM(ac.ac_amount),0) from t_actress_credit ac join t_order o on o.o_id = ac.order_id where o.o_status = 1 and ac.ac_is_paid = 1 and ac.actress_id = a.a_id and ac.ac_time>[email protected]_from and ac.ac_time<[email protected]_to) as paid_credit
,(select COUNT(1) from t_message pm join t_call_log l1 on pm.call_log_id = l1.c_id where pm.m_type = 2 and l1.caller_id = c.c_id and pm.m_time>[email protected]_from and pm.m_time<[email protected]_to) as pmsg_sent
,(select COUNT(1) from t_message pm join t_call_log l2 on pm.m_to_call_log_id = l2.c_id where pm.m_type = 2 and l2.caller_id = c.c_id and pm.m_time>[email protected]_from and pm.m_time<[email protected]_to) as pmsg_received
,(select COUNT(1) from t_message pm join t_call_log l3 on pm.call_log_id = l3.c_id where pm.m_type = 1 and l3.caller_id = c.c_id and pm.m_time>[email protected]_from and pm.m_time<[email protected]_to) as lcmsg_sent
,(select COUNT(1) from t_message pm join t_call_log l4 on pm.m_to_call_log_id = l4.c_id where pm.m_type = 1 and l4.caller_id = c.c_id and pm.m_time>[email protected]_from and pm.m_time<[email protected]_to) as lcmsg_received
,(select COUNT(1) from t_actress_live_minute where actress_id = a.a_id and alm_time>[email protected]_from and alm_time<[email protected]_to) as live_calls
,(select isnull(SUM(alm_minutes),0) from t_actress_live_minute where actress_id = a.a_id and alm_time>[email protected]_from and alm_time<[email protected]_to) as live_call_minutes
,(select isnull(count(1),0) from t_call_log l where l.caller_id = c.c_id and l.c_time_out is not null and c_time_in >[email protected]_from and c_time_in <= @time_to) as total_calls
,(select isnull(SUM(DATEDIFF(minute, l.c_time_in, l.c_time_out)),0) from t_call_log l where c_time_in >[email protected]_from and c_time_in <= @time_to and l.caller_id = c.c_id and l.c_time_out is not null) as total_call_minutes
from t_actress a
join t_caller c on c.c_id = a.caller_id
group by a.a_id,c.c_id, c.c_chat_line_id, a.a_first_name, a.a_last_name
任何一個可以給出一些建議嗎?
非常感謝!
艾倫
,我會做的第一件事是註釋掉所有的子查詢,看看外部查詢需要多長時間運行,假設它的快速一次添加一個子查詢,看看哪些是造成下跌的最慢。 – 2013-03-13 20:48:09
請向我們展示執行計劃。 – 2013-03-13 20:48:12
從你的表名中,我猜測消息的計數將是最慢的操作。 – grahamj42 2013-03-13 20:50:08