这是我的SQL命令:
SELECT
ts.CHECK_NUMBER,
ts.CUSTOMER_NAME,
ts.COMPANY_NAME,
( SELECT COUNT(*)
FROM TRANSACTION_ORDER too
WHERE too.CHECK_NUMBER = ts.CHECK_NUMBER
) as NB_OF_ORDERS
FROM
TRANSACTION_SUMMARY ts
ORDER BY
ts.BUSINESS_DATE
渲染数据需要很长时间,我们正在讨论最少3000笔交易,我们必须为每笔交易计算订单。
有没有更好的解决方案?
答案 0 :(得分:2)
这需要太长时间,因为当你在select中有这个子查询时,它会对外部查询返回的每一行执行,所以如果你的外部查询返回50,000行,那么这个内部select查询将被执行50,000次显然是性能杀手,
你应该尝试这样的事情......
SELECT
ts.CHECK_NUMBER
,ts.CUSTOMER_NAME
,ts.COMPANY_NAME
,ISNULL(O.Total, 0) AS NB_OF_ORDERS
FROM TRANSACTION_SUMMARY ts
LEFT JOIN --<-- use inner join is you only want records with some orders
( SELECT CHECK_NUMBER, COUNT(*) AS Total
FROM TRANSACTION_ORDER
GROUP BY CHECK_NUMBER
) as O
ON ts.CHECK_NUMBER = O.CHECK_NUMBER
ORDER BY ts.BUSINESS_DATE