这是一个需要400秒加载的查询。我直接尝试了mysql。如果我单独尝试子查询,所有都会在不到0.01秒的时间内执行。 在40秒内查询afer union所有exuecutes。联合之前的查询全部在1秒内执行。
sales表和salesaff表都包含大约12K条记录。此查询的目的是当sales = affiliate in sales table时,我需要添加salesaff表中的行,其中id与sales表中的搜索条件匹配。
(
SELECT 'no' AS aff, ss.orderid,ss.saletype,ss.price,ss.salests
FROM sales ss
WHERE 1=1 AND
( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade')
)
UNION ALL
(
SELECT 'yes' AS aff, sf.orderid,sf.saletype,sf.price,sf.salests
FROM salesaff sf
WHERE sf.vendor=sf.affiliate AND
sf.orderid IN (SELECT ss.orderid from sales ss WHERE 1=1
AND ( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade')
GROUP BY ss.orderid )
)
ORDER BY salests DESC
答案 0 :(得分:0)
尝试启动此功能:
EXPLAIN ( SELECT 'no' AS aff, ss.orderid,ss.saletype,ss.price,ss.salests FROM sales ss WHERE 1=1 AND ( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade') )
UNION ALL
( SELECT 'yes' AS aff, sf.orderid,sf.saletype,sf.price,sf.salests FROM salesaff sf WHERE sf.vendor=sf.affiliate AND
sf.orderid IN ( SELECT ss.orderid from sales ss WHERE 1=1 AND ( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade') GROUP BY ss.orderid ) )
ORDER BY salests DESC
检查“key”列是否永远不为null,否则将索引添加到提到的列中。
这没有用,请查看以下答案:https://dba.stackexchange.com/questions/7806/copying-to-tmp-table-extremely-slow
答案 1 :(得分:0)
我认为它正在尝试在查询执行期间进行排序。这可能会有所帮助:
SELECT * FROM (
(
SELECT 'no' AS aff, ss.orderid,ss.saletype,ss.price,ss.salests
FROM sales ss
WHERE 1=1 AND
( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade')
)
UNION ALL
(
SELECT 'yes' AS aff, sf.orderid,sf.saletype,sf.price,sf.salests
FROM salesaff sf
WHERE sf.vendor=sf.affiliate AND
sf.orderid IN (SELECT ss.orderid from sales ss WHERE 1=1
AND ( ss.vendor='3kpertrade' OR ss.affiliate='3kpertrade')
GROUP BY ss.orderid )
)
)
ORDER BY salests DESC