mysql - 查询需要很长时间才能执行

标签 mysql

我有以下查询,我使用之间的运算符来获取特定数字之间年龄的记录,但查询需要花费大量时间来显示结果,其时间超过 5 分钟它仍在运行

SELECT
  *,
  (SELECT COUNT(*)
   FROM users
   WHERE
     1=1 OR
     LOWER(age) BETWEEN 18 AND 20 OR
     LOWER(age) BETWEEN 20 AND 25 OR
     LOWER(age) BETWEEN 25 AND 30 OR
     LOWER(age) BETWEEN 30 AND 35
  ) AS totalcount
FROM users, states, countries, user_types, media
WHERE
  users.id_user_type = user_types.id AND
  users.id_state = states.id AND
  users.id_country = countries.id AND
  media.id_user = users.id AND
  media.profile_photo = 1 AND
  users.id_user_type = 3 OR
  LOWER(age) BETWEEN 18 AND 20 OR
  LOWER(age) BETWEEN 20 AND 25 OR
  LOWER(age) BETWEEN 25 AND 30 OR
  LOWER(age) BETWEEN 30 AND 35
ORDER BY users.id 

令人不安的部分是:

LOWER(age) BETWEEN 18 AND 20 OR
LOWER(age) BETWEEN 20 AND 25 OR
LOWER(age) BETWEEN 25 AND 30 OR
LOWER(age) BETWEEN 30 AND 35

最佳答案

避免使用您拥有的 or 子句(它没有意义)。您的查询可能执行了大量的 CROSS JOIN 操作,这就是它花费太长时间的原因(您的结果集非常大)。

 select *,
        (
            select count(*) 
              from users 
             where 1=1 
                or lower(age) between 18 and 20 
                or lower(age) between 20 and 25 
                or lower(age) between 25 and 30 
                or lower(age) between 30 and 35
        ) as totalcount 
   from users, states, countries, user_types, media 
  where users.id_user_type = user_types.id 
    and users.id_state = states.id 
    and users.id_country = countries.id 
    and media.id_user = users.id 
    and media.profile_photo = 1 
    and users.id_user_type = 3 
  order by users.id 

此外,还不清楚您想通过此查询完成什么任务。

回答这些问题可能有助于我们为您提供帮助:

  1. age 列类型是什么
  2. 您对内心查询到底有何期望

关于mysql - 查询需要很长时间才能执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699475/

相关文章:

mysql - 无法将值插入 Heroku 数据库

php - 使用 Cast Mysql 将时间戳转换为 MM-DD-YY

mysql - 需要棘手的 sql 查询,查找子查询的总和

php - 如何让 PHP while 语句终止?

php - MySQL 枚举与整数

mysql - Ubuntu MySQL : Job failed to start

php - 数据库变化检测

php - PDO : get result from SELECT query

mysql - 如何统计Mysql中特定列的字段数?

MySQL 查询从单个表中查找相关行