Mysql 关联查询的问题
在写业务时,遇到查询,因为数据量增大,导致查询时间冲着 5s 去了,想了一天也不知道该怎么优化,来求各位大佬支个招。
(1)三张表,每张表都有 5000 条左右的数据。
(2)consume 是主表,分别和 org 表和 admin 表有“一对多”关系。
(3)现需要对三张表进行联合查询,查询结果去重排序。
最开始使用的语句是,时间超过 10s 了:
SELECT * FROM consume WHERE uid IN ( SELECT c.uid FROM consume AS c LEFT JOIN consume_admin AS a ON c.uid=a.consume_id AND a.deleted=0 LEFT JOIN consume_org AS o ON o.consume_id=c.uid AND o.deleted=0 WHERE c.deleted=0 and a.deleted=0 and o.deleted=0 AND (a.user_id='126949' OR c.create_user_id='126949')) order by create_at desc;
然后百度了一下,稍微改进了一下,但还是不如意:
select c.* FROM consume AS c LEFT JOIN consume_admin AS a ON c.uid=a.consume_id AND a.deleted=0 LEFT JOIN consume_org AS o ON o.consume_id=c.uid AND o.deleted=0 WHERE c.deleted=0 and a.deleted=0 and o.deleted=0 AND (a.user_id='126949' OR c.create_user_id='126949') group by c.uid order by c.create_at desc;
求各位大佬帮帮忙了!!
PS:发现把 admin 表和 org 表单独查一次,然后取到的 consume_id 再到 consume 表里用 uid IN 查询会更快,但是我看百度里说都是直接联表查询比这种分步的快,是我写的 sql 太差了么。
#悬赏#