小编Tom*_*ock的帖子

即使使用索引,Mysql 查询仍然很慢

我试图优化我用来根据地址从数据库中获取客户的 mysql 查询。这个问题让我发疯,所以我很感激帮助:)

我有两个与此查询相关的表:customers_address 和 systems_address。我只想获得我可以为该系统显示地址的客户。

例子:

我想从customers_address表中获取客户,这些客户的address_id属于system_id 2。

使用 in 子句的最佳查询:

select distinct customer_id from customers_address use index(address_id_customer_id) where address_id in (select distinct address_id from systems_address where system_id = 2) and address_id !=-1\G;
Run Code Online (Sandbox Code Playgroud)

问题是子查询只返回一行(值 2),如果我使用子查询值运行整个查询,它真的很快:

select customer_id from customers_address use index(address_id_customer_id) where address_id !=-1 and address_id in (2)\G;
Run Code Online (Sandbox Code Playgroud)

时间从超过 10 秒下降到 0.00 秒。

我也尝试过使用连接进行查询,但是当我将值替换为 in 子句时与查询进行比较时,它的性能仍然很慢(超过 7 秒)。在带有连接的相同查询下:

select distinct customer_id from customers_address use index(address_id_customer_id) inner join systems_address where systems_address.address_id = customers_address.address_id and system_id = 2 and customer_id != …
Run Code Online (Sandbox Code Playgroud)

mysql query-optimization

5
推荐指数
1
解决办法
2531
查看次数

标签 统计

mysql ×1

query-optimization ×1