gpt4 book ai didi

mysql - 如何优化这条SQL语句?

转载 作者:行者123 更新时间:2023-11-29 06:30:01 26 4
gpt4 key购买 nike

我需要根据一个表 (tableA) 的选择结果从表列表 (list1,list2,list3,...) 中进行选择。如何重用该表 (tableA) 中的选择结果?

我的解决方案是

select * from list1 where list1.id in(select id from tableA where ...)
select * from list2 where list2.id in(select id from tableA where ...)
select * from list3 where list3.id in(select id from tableA where ...)
...

在我的解决方案中,select id from tableA where ...执行了3次,可能会耗费很多时间,效率不高。在我的想象中,select id from tableA where ... 应该只执行一次。

谁能帮帮我?

最佳答案

有两点需要注意。首先,在某些版本的 MySQL 中,exists 版本效率更高:

select *
from list1
where exists (select 1 from tableA a where a.id = list1.id and (...))
. . .

其次,您希望在 tableA 上拥有正确的索引以优化查询。基本上,右索引是一个复合索引,其中第一个键是 id,后面是 where 子句中的列。

对索引中的列进行排序的最佳方式取决于 where 条件。如果条件都是由 连接的相等条件,那么顺序无关紧要。

关于mysql - 如何优化这条SQL语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28515744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com