在mysql表中存储多个范围,以便更快/更容易地进行查询

时间:2014-02-18 10:41:43

标签: mysql sql performance date-range

我有一个包含多个时间范围的数据,例如请考虑以下列

| from1 |  to1  | from2 |  to2  | from3 |  to3  |

| 06:00 | 07:30 | 09:30 | 12:30 | 13:30 | 15:45 |
| 05:00 | 06:30 | 08:15 | 14:40 | 16:30 | 18:25 |

现在,如果我想搜索时间08:30,我将不得不在查询中添加3个子句以匹配输入是否在所有三个从 - 到对中的任何一个范围内。

在上面的情况中,它将返回第二行,因为08:30位于第二个从 - 对中。

我想知道这样做的最佳做法是什么?即使我必须更改我的数据模型并且不将这些范围存储在如上所示的列中,也可以。这样我就可以快速轻松地搜索成千上万的记录

我想不出更好的替代方案,请建议。

2 个答案:

答案 0 :(得分:0)

当我在寻找这个问题时,我发现了这一点。

您的数据模型似乎未规范化。您应该考虑关于创建附加表的morjas建议。

下面是一个非常难看的查询,它检查日期是否在三个范围中的任何一个,然后返回匹配率。

select case 
when date '2010-12-05' between range1_from and range1_to then range1_rate
when date '2010-12-05' between range2_from and range2_to then range2_rate
when date '2010-12-05' between range3_from and range3_to then range3_rate
end as rate
from events
where date '2010-12-05' between range1_from and range1_to
or date '2010-12-05' between range2_from and range2_to
or date '2010-12-05' between range3_from and range3_to;

REF。SQL query for finding a value in multiple ranges

答案 1 :(得分:0)

将您的时间存储为DATETIME并使用BETWEEN

所以:

where myDate BETWEEN '2011-03-18 08:30' AND '2011-09-18 09:00'