【问题标题】:Where clause containing date in MySQL statement not working在 MySQL 语句中包含日期的 Where 子句不起作用
【发布时间】:2015-04-20 09:51:26
【问题描述】:

表名:DemoTable

总字段:2

字段:

id (int, auto increment, primary key)
month_and_year (varchar(10))

month_and_year 包含日期为“2015-03”、“2015-01”、“2014-12”等...

我正在尝试从“2014-10”和“2015-03”之间的表中获取值。

SELECT * FROM DemoTable where month_and_year>='2014-10' AND month_and_year<='2015-03' ORDER BY month_and_year DESC 

查询没有提供所需的输出,因为 month_and_year 字段具有 varchar 数据类型。无法将 varchar 更改为日期数据类型,因为日期数据类型不接受 'yyyy-mm' 格式的日期。

如何获得结果?

PS:在这种情况下,UNIX_TIMESTAMP() 是否安全?

【问题讨论】:

    标签: mysql date


    【解决方案1】:

    您不应该将日期值存储为 varchar 并选择 mysql 本机日期相关数据类型,例如 datedatetimetimestamp

    但是,在您的情况下,您需要在执行选择查询之前进行一些与日期相关的计算。考虑下表

    mysql> select * from test ;
    +------+----------------+
    | id   | month_and_year |
    +------+----------------+
    |    1 | 2014-10        |
    |    2 | 2014-10        |
    |    3 | 2014-09        |
    |    4 | 2014-11        |
    |    5 | 2015-01        |
    |    6 | 2014-08        |
    +------+----------------+
    

    现在的方法是

    首先将varchar转换为真实日期

    那么对于下限总是从一年的第一天开始比较月份值

    上限将持续到月底。

    所以查询变成了

    select * from test
    where 
    date_format(
     str_to_date(
         month_and_year,'%Y-%m'
     ),'%Y-%m-01'
    ) 
    >= 
    date_format(
      str_to_date('2014-10','%Y-%m'
      ),'%Y-%m-01'
    ) 
    and 
    last_day(
       date_format(
         str_to_date(month_and_year,'%Y-%m'
         ),'%Y-%m-01'
       )
    ) 
    <= 
    last_day(
       date_format(
        str_to_date('2015-03','%Y-%m'
        ),'%Y-%m-01'
       )
    );
    

    输出将是

    +------+----------------+
    | id   | month_and_year |
    +------+----------------+
    |    1 | 2014-10        |
    |    2 | 2014-10        |
    |    4 | 2014-11        |
    |    5 | 2015-01        |
    +------+----------------+
    

    【讨论】:

      【解决方案2】:

      使用函数STR_TO_DATE(string,format);

      http://www.mysqltutorial.org/mysql-str_to_date/

      【讨论】:

        【解决方案3】:

        您应该使用 mysql 日期时间 functions 或使用 mysql 中的 int 字段并存储 UNIXTIMESTAMP 并像您已经在做的那样进行比较。我认为存储 unixtimestamp 太过分了,因为您只需要月份和年份,而且您不会从 unixtimestamp 的优势中受益匪浅。

        【讨论】:

        • 我不需要存储整个日期。我只需要'yyyy-mm'。这就是我选择这条路的原因。有什么解决方法吗? UNIX_TIMESTAMP() 是唯一的。所以,我不能只以“yyyy-mm”格式传递我的日期作为参数并将生成的时间戳存储在数据库中。那个怎么样? @RuslanN
        • @SajeevC 只使用 mysql 日期时间格式并使用日期时间函数进行比较
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多