关于 mysql 优化,请教大神们~

2020-04-09 15:52:02 +08:00
 gonethen

查询结果才一万多条就用了 60s,请问大神们这句 sql 还有什么可优化的空间?


SELECT
	count(tto.id)
FROM tb_order o
LEFT JOIN (SELECT
		id,
		trucker_order_id,
		parents_id,
		carrier_org_name,
		fence_status
	FROM tb_order
	WHERE fence_status = '1'
	AND IFNULL(trucker_order_id, 1) != 1
) so ON FIND_IN_SET(o.id, so.parents_id)
LEFT JOIN tb_transport tt ON tt.order_id = so.id
LEFT JOIN tb_trucker_order tto ON tto.id = so.trucker_order_id
WHERE o.org_id = '153645643245457'
AND IFNULL(so.id, 1) != 1;

1320 次点击
所在节点    问与答
16 条回复
shoaly
2020-04-09 16:03:22 +08:00
用代码去做逻辑, 不要用 mysql 去编程....
大部分情况 mysql 只需要查一个表, 极少数才会连 2 个表
AngryPanda
2020-04-09 16:07:45 +08:00
@shoaly 那是你没做 ERP 之类的内部系统
jjianwen68
2020-04-09 16:09:10 +08:00
先 explain 看看
Vegetable
2020-04-09 16:09:47 +08:00
问这种问题带个 DDL 朋友...
show create table `tablename`;
tomczhen
2020-04-09 16:10:12 +08:00
自己看 explain,大神都快饿死了。
ic2y
2020-04-09 16:11:57 +08:00
你表结构都没有,没有索引之类的 信息,大家怎么帮你看呢?
chihiro2014
2020-04-09 16:14:11 +08:00
先 explain 分析下情况再看
gonethen
2020-04-09 16:15:18 +08:00
@jjianwen68 #3
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY o ref org_id org_id 195 const 20391 Using where; Using index
1 PRIMARY <derived2> ALL 40783 Using where; Using join buffer (Block Nested Loop)
1 PRIMARY tt ref oder_id oder_id 195 so.id 1 Using index
1 PRIMARY tto eq_ref PRIMARY PRIMARY 194 so.trucker_order_id 1 Using index
2 DERIVED tb_order ALL 40783 Using where
dapang1221
2020-04-09 16:15:31 +08:00
WHERE fence_status = '1' AND IFNULL(trucker_order_id, 1) != 1
这啥玩意?直接 and trucker_order_id is not null 不行么……这玩意肯定全表扫了啊

ON FIND_IN_SET(o.id, so.parents_id)
还有这啥? join xx on x.id = xx.pid 然后 where 里加一个 xx.pid is not null 就行啊
dilu
2020-04-09 16:15:58 +08:00
SET profiling = 1;
#执行语句
show profiles;
show profile block io,cpu for query 1;

第二行换成你的 sql 跑一下贴结果来看看
dapang1221
2020-04-09 16:16:07 +08:00
有一说一我真就头一回见到 IFNULL 和 FIND_IN_SET 这俩东西,也许是我才疏学浅了吧……
gonethen
2020-04-10 09:33:24 +08:00
gonethen
2020-04-10 09:48:50 +08:00
@dapang1221 #9 parents_id 是以逗号隔开的多级父级 id,数据表结构是之前设计的锅,我不背
dilu
2020-04-10 10:07:54 +08:00
就执行结果来看 你这速度一点不慢啊 这个慢是偶发的还是必现的?
gonethen
2020-04-10 10:48:29 +08:00
@dilu #14 必现的。10k 的数据需要 60s 肯定是不行的,所以我想要优化一下
dilu
2020-04-10 11:29:06 +08:00
@gonethen 微信沟通吧 emh3MTk5NDA0MTI=

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/660829

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX