mysql - 查询执行时间超过 40 秒

标签 mysql sql

在具有 20 万行的表上执行此查询需要超过 40 秒

SELECT 
     my_robots.*, 
     (
        SELECT count(id) 
        FROM hpsi_trading 
        WHERE estado <= 1 and idRobot = my_robots.id
     ) as openorders,
     apikeys.apikey, 
     apikeys.apisecret 
FROM my_robots, apikeys 
WHERE estado <= 1 
     and idRobot = '2' 
     and ready = '1' 
     and apikeys.id = my_robots.idApiKey 
     and (my_robots.id LIKE '%0' 
          OR my_robots.id LIKE '%1' 
          OR my_robots.id LIKE '%2') 

我知道这是因为查询内的计数,但我怎样才能有效地解决这个问题。

编辑:解释

enter image description here

谢谢。

最佳答案

使用GROUP BY代替

SELECT my_robots.*, 
       count(id) as openorders, 
       apikeys.apikey, 
       apikeys.apisecret 
FROM my_robots
JOIN apikeys ON apikeys.id = my_robots.idApiKey
LEFT JOIN hpsi_trading ON hpsi_trading.idRobot = my_robots.id and estado <= 1
WHERE estado <= 1 and 
      idRobot = '2' and 
      ready = '1' and 
      (
          my_robots.id LIKE '%0' OR 
          my_robots.id LIKE '%1' OR 
          my_robots.id LIKE '%2'
      ) 
GROUP BY my_robots.id, apikeys.apikey, apikeys.apisecret

使用显式的JOIN语法。需要一些索引才能快速运行它,但是,从您的帖子(以及您的查询)来看,数据库结构尚不清楚。

关于mysql - 查询执行时间超过 40 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749827/

相关文章:

java - jooq 是否比 java 中的简单 sql 有任何性能领先

mysql - 合并 id 重叠的 2 个表

sql - 如何防止 SQL Server 对扫描的行数进行平方?

sql - 我怎样才能做一个不同的总和?

mysql - 如何在 MySQL 中正确地字符串标记

PHP 和 Mysql、nl2br 和验证错误

mysql - 选择一个项目,该项目在数据库中重复出现的总次数以及该项目状态为1的次数

mysql - 查询问题之间的 JPA hibernate 日期

php - SQL Where NOT Exists 插入

sql - 如何使用PROC SQL查找数值变量的长度