【发布时间】:2014-11-14 16:47:03
【问题描述】:
问题:给定一系列可为空的开始日期和结束日期,优化以下查询的最佳方法是什么(底部的示例架构): p>
-- Query I am trying to optimize
SELECT * FROM dateranges WHERE
('2014-11-10 05:59:59' > `start` AND '2014-11-03 06:00:00' <= `end`)
OR ('2014-11-03 06:00:00' >= `start` AND `end` is null)
OR ('2014-11-10 05:59:59' <= `end` AND `start` is null);
-- Same query but with placeholders for clarification
SELECT * FROM dateranges WHERE
('{endSearch}' > `start` AND '{startSearch}' <= `end`)
OR ('{startSearch}' >= `start` AND `end` is null)
OR ('{endSearch}' <= `end` AND `start` is null);
商业条件有效:
- name.start >= startSearch AND endSearch 吗?
- name.start >= startSearch AND name.end 是否为空?
- name.end endSearch AND name.start 是否为空?
下面显示EXPLAIN只是搜索开始和结束:
1, SIMPLE, s, range, date_start_idx,date_end_idx, date_end_idx, 6, , 251, Using index condition; Using where; Using temporary; Using filesort
下面显示 EXPLAIN 添加了空搜索:
1, SIMPLE, s, ALL, date_start_idx,date_end_idx, , , , 6340, Using where; Using temporary; Using filesort
MySQL 架构示例:
CREATE TABLE `dateranges` (
`name` VARCHAR(45) NULL,
`start` DATETIME NULL,
`end` DATETIME NULL);
INSERT INTO `dateranges` (`name`,`start`,`end`) VALUES
('God',null,null),
('Dog',null,'2014-10-06'),
('Cat','2014-10-01',null),
('People','2014-10-02','2014-10-04');
ALTER TABLE `dateranges`
ADD INDEX `index1` (`start` ASC),
ADD INDEX `index2` (`end` ASC);
【问题讨论】:
-
在第一个条件中添加“start is not null”和“end is not null”将有助于消除所有空值。
-
这个查询搜索什么?包含在指定日期内的记录还是与指定日期重叠/冲突的记录?
-
@SalmanA 查询返回用于内容搜索的名称 ID。有些名称可以有内容的开始时间,但没有结束时间。