Mysql执行时间太长

时间:2017-08-11 09:41:07

标签: mysql

我的桌子上有2百万条记录。当我执行一个有3 where condition的查询时,响应时间太长。

查询

SELECT COUNT(*) 
  FROM `table` 
 WHERE DATE(`created_at`) = '2017-08-11' 
   AND `type` in (4,13,15) 
   AND `status` = 1

执行时间:3秒

如何减少此查询或此类查询的执行时间?

修改

表架构

CREATE TABLE `transactions` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `type` int(11) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '2',
  `created_at` timestamp NULL DEFAULT NULL,
  ...
  PRIMARY KEY (`id`),
  KEY `query` (`created_at`,`type`,`status`),
  KEY `query2` (`status`,`type`)

我不知道我的索引是否正确

3 个答案:

答案 0 :(得分:1)

尝试分离IN子句。我亲身经历IN子句使查询变慢,因为内部MySQL假定全表扫描并在某些情况下忽略索引。此外,DATE(created_at)将完全忽略该索引,因为它在日期时间编制索引。

您可以尝试以下UNION查询并希望它加快输出速度:

SELECT SUM(total) AS total
  FROM (
    SELECT COUNT(*) AS total
      FROM `table` 
    WHERE `created_at` BETWEEN '2017-08-11 00:00:00' AND  '2017-08-11 23:59:59'
      AND `type` = 4 
      AND `status` = 1
    UNION
    SELECT COUNT(*) AS total
      FROM `table` 
    WHERE `created_at` BETWEEN '2017-08-11 00:00:00' AND  '2017-08-11 23:59:59'
      AND `type` = 13 
      AND `status` = 1
    UNION
    SELECT COUNT(*) AS total
      FROM `table` 
    WHERE `created_at` BETWEEN '2017-08-11 00:00:00' AND  '2017-08-11 23:59:59'
      AND `type` = 15 
      AND `status` = 1
  ) z;

您还可以添加仅包含date的列或从created_at中移除时间,并将其存储在新的time列中,如果现有系统可行的话。

答案 1 :(得分:0)

可能需要一个合适的索引,例如:

  create index  my_new_index on `table`  ( date(`created_at`), `type`,  `status` );

答案 2 :(得分:0)

替换

KEY from Tkinter import * from PIL import Image import io class Window: def __init__(self, master): master.title("Image Processing test") master.minsize(800, 400) im = Image.open("IMG_0562.png") size = 240, 240 im.thumbnail(size) b = io.BytesIO() im.save(b, 'gif') p = b.getvalue() photo = BitmapImage(data=p) w = Label(root, image=photo, width=240, height=240).grid(row=20, column=2) self.photo = photo root = Tk() window = Window(root) root.mainloop() querycreated_attype),

KEY statusquery2status),

KEY typecreated_at),

KEY created_attype),

KEY typestatus),

我认为它会更快。此外,您必须将类型和状态的数据类型转换为tinyint,smallint,如果可能,则应添加无符号约束,它永远不会签名。