我遇到一个非常大的MYSQL查询问题,该查询处理超过10分钟以显示记录。
查询如下所示:
SELECT SQL_CALC_FOUND_ROWS * FROM (
SELECT 't-0' as typo, sh_inquiry.id as ref, sh_inquiry.pid as pid, partner, sh_inquiry.order, if(p_status IS NULL OR p_status = 0,'not paid','paid') as payment, p_voucher, country, city, delivery_date, sh_inquiry.amount as c_amount, currency as c_currency, NULL as s_amount, NULL as s_currency, IF(confirmed=0,if(delivered=0,"not confirmed","delivered"),if(delivered=0,"confirmed","delivered")) as conf
FROM sh_inquiry
LEFT JOIN sh_orders ON sh_inquiry.id = sh_orders.i_id
LEFT JOIN sh_partners ON sh_partners.pid = sh_inquiry.pid
LEFT JOIN sh_currency ON sh_currency.id = sh_inquiry.curr_id
LEFT JOIN sh_country ON sh_country.id = sh_inquiry.cid
LEFT JOIN sh_debts ON sh_inquiry.id = sh_debts.i_id
WHERE sh_inquiry.del = 0 AND sh_inquiry.type = 1 AND sh_orders.del = 0
UNION
SELECT 't-1' as typo, sh_orders.i_id as ref, sid as pid, partner, sh_inquiry.order, if(p_status IS NULL OR p_status = 0,'not paid','paid') as payment, p_voucher, country, city, delivery_date, NULL as c_amount, NULL as c_currency, sh_orders.amount as s_amount, currency as s_currency, IF(confirmed=0,if(delivered=0,'not confirmed','delivered'),if(delivered=0,'confirmed','delivered')) as conf FROM sh_orders
LEFT JOIN sh_partners ON sh_partners.pid = sh_orders.sid
LEFT JOIN sh_currency ON sh_currency.id = sh_orders.curr_id
LEFT JOIN sh_inquiry ON sh_inquiry.id = sh_orders.i_id
LEFT JOIN sh_country ON sh_country.id = sh_inquiry.cid
LEFT JOIN sh_debts ON sh_orders.id = sh_debts.o_id
WHERE sh_orders.del = 0 AND sh_inquiry.del = 0
) AS U
ORDER BY typo ASC, delivery_date
asc
LIMIT 0, 10
问题是我使用的是必须连接在一起的2个表(这两个表非常大),这就是我使用UNION语句的原因。我在jquery datatables服务器端页面中显示记录,因此限制显示的记录无助于原因。
有人能想出加快这个查询的想法吗? 如果您需要有关数据库结构的更多信息,请询问。
EXPLAIN声明解雇了:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 17630 Using filesort
2 DERIVED sh_orders ALL i_id NULL NULL NULL 8696 Using where
2 DERIVED sh_inquiry eq_ref PRIMARY,id PRIMARY 4 reur3918_sh.sh_orders.i_id 1 Using where
2 DERIVED sh_partners eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_inquiry.pid 1
2 DERIVED sh_currency eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_inquiry.curr_id 1
2 DERIVED sh_country eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_inquiry.cid 1
2 DERIVED sh_debts ALL NULL NULL NULL NULL 18678
3 UNION sh_orders ALL i_id NULL NULL NULL 8696 Using where
3 UNION sh_partners eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_orders.sid 1
3 UNION sh_currency eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_orders.curr_id 1
3 UNION sh_inquiry eq_ref PRIMARY,id PRIMARY 4 reur3918_sh.sh_orders.i_id 1 Using where
3 UNION sh_country eq_ref PRIMARY PRIMARY 4 reur3918_sh.sh_inquiry.cid 1
3 UNION sh_debts ALL NULL NULL NULL NULL 18678
NULL UNION RESULT <union2,3> ALL NULL NULL NULL NULL NULL
索引所有id后,查询大约需要133秒..
答案 0 :(得分:0)
谢谢大家的想法! 实际上,运行EXPLAIN语句帮助我找到没有定义INDEX的表。 将INDEX添加到已用于查询的所有字段(主要在JOIN ON子句中)后,运行时间减少到0.83秒