【发布时间】:2018-03-04 05:57:22
【问题描述】:
我们有一个 event mysql 表,我们在其中存储从不同类型的传感器生成的事件。下面是同一张表的创建表查询。
CREATE TABLE `event` (
`id` varchar(36) NOT NULL,
`device_id` varchar(36) NOT NULL,
`device_type` varchar(45) NOT NULL,
`data` text NOT NULL,
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_event_device_idx` (`device_id`),
KEY `event_device_type` (`device_type`),
KEY `event_created_at_idx` (`created_at`),
CONSTRAINT `fk_event_device` FOREIGN KEY (`device_id`) REFERENCES `device` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
我们有一个来自 device 表的 device_id 外键,而设备表有一个来自 zone 的 zone_id 外键强>表。
我们想要获取特定 zone 和 device_type(例如 THL 传感器) 在某个日期(例如 2017 年 2 月 26 日)的事件。下面是我正在运行的查询。
select e.data from event e
left join device d on d.id = e.device_id
where d.type = 'mdc' and d.zone_id = 'e451b2a1-5f6c-4a75-8038-30854926a9c0' and DATE(e.created_at) = '2018-03-01';
解释计划给出了相同的结果。
+----+-------------+-------+------------+------+--------------------------------------+---------------------+---------+--------------+------+----------+------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+--------------------------------------+---------------------+---------+--------------+------+----------+------------------------------------+
| 1 | SIMPLE | d | NULL | ref | PRIMARY,id_UNIQUE,fk_device_zone_idx | fk_device_zone_idx | 110 | const | 23 | 10.00 | Using index condition; Using where |
| 1 | SIMPLE | e | NULL | ref | fk_event_device_idx | fk_event_device_idx | 110 | senzopt.d.id | 197 | 100.00 | Using where |
+----+-------------+-------+------------+------+--------------------------------------+---------------------+---------+--------------+------+----------+------------------------------------+
事件表中的记录总数约为 500 万条,上述查询大约需要 1 秒的时间来执行并提供结果。我希望改善 sql 执行时间。需要相同的建议。请让我知道我能做对的所有事情。
注意:我知道我应该迁移到 NOSQL(Kafka/Cassandra/Spark) 来做同样的事情。为此,我们也在并行工作。但是,我希望改进查询,以便在当前情况下更好地为我的客户服务。
【问题讨论】:
标签: mysql