【问题标题】:How to search through date_format field in MySQL如何在 MySQL 中搜索 date_format 字段
【发布时间】:2012-12-15 19:32:54
【问题描述】:

我已经更改了字段的日期格式,但是它没有找到新日期模式的记录。

SELECT id, DATE_FORMAT(sale_date, "%d-%m-%Y") AS sale_date 
FROM sales 
WHERE sale_date = '31-12-2012';

【问题讨论】:

    标签: mysql sql date select


    【解决方案1】:

    假设您为列sale_date 使用timestampdate 格式,则必须指定日期,如YYYY-MM-DD:

        WHERE sale_date = '2012-12-31';
    

    【讨论】:

    • @TPSstar: Mysql always 使用ISO8601 format 在表达式中写入日期。
    • @Ray 是的,我知道,但我想搜索我定义的格式,即“%d-%m-%Y”
    • @TPSstar 抱歉,您的问题并未表明您无法更改提供的字符串。 Saharsh 在上面回答中的第二个查询应该可以解决问题。
    【解决方案2】:

    试试这个:

    SELECT id, DATE_FORMAT(sale_date, "%d-%m-%Y") AS sale_date 
    FROM sales 
    WHERE sale_date = STR_TO_DATE('31-12-2012' , "%d-%m-%Y") ;
    

    SELECT id, DATE_FORMAT(sale_date, "%d-%m-%Y") AS sale_date 
    FROM sales 
    WHERE DATE_FORMAT(sale_date, "%d-%m-%Y") = '31-12-2012';
    

    【讨论】:

    • 确实,这会起作用,但是将 where 子句中的 DATE_FORMAT 函数应用于 sale_date 列会导致它忽略列 sale_date 上的任何索引...我会假设他们是通过 sale_date 查找,他们已将其编入索引。
    • 检查我的其他查询,它将应用 indexon sale date 列
    • 是的,第二次查询不会破坏索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2020-10-04
    • 2011-03-21
    • 2021-10-15
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多