【问题标题】:Store multiple ranges in mysql table to make queries faster/easier在 mysql 表中存储多个范围以使查询更快/更容易
【发布时间】:2014-02-18 10:41:43
【问题描述】:

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

| 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 位于第二个从对对中。

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

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

【问题讨论】:

    标签: mysql sql performance date-range


    【解决方案1】:

    我在搜索这个问题时发现了这个。

    您的数据模型似乎没有标准化。您应该考虑 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;
    

    参考SQL query for finding a value in multiple ranges

    【讨论】:

    • 对不起,我应该提到它。查询中所需的数据已经存储在 4 个不同的表中,我不确定是否应该再添加一个表来进行 5 表连接查询。
    【解决方案2】:

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

    所以:

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

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2021-02-15
      • 2015-06-02
      • 1970-01-01
      • 2012-05-27
      • 2021-07-02
      • 2021-07-21
      • 2017-04-26
      • 2022-01-13
      相关资源
      最近更新 更多