php SQL 查询以给定日期/时间格式选择当前或特定月份的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11665487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:50:24  来源:igfitidea点击:

SQL query to select values for a current or specific month in a given date/time format

phpmysqlsql

提问by LiveEn

I have saved the date in the database (mysql) as (d-m-Y H:i:s)

我已将数据库(mysql)中的日期保存为 (d-m-Y H:i:s)

How can write a sql query to select all the values that are only for the current month or a specific month ?

如何编写 sql 查询来选择仅适用于当月或特定月份的所有值?

回答by Festim

SELECT *
FROM table
WHERE DATE_FORMAT(date_field,'%m-%Y') = '07-2012';

回答by Sherlock

Store your dates in MySQL DATE format and use the following query:

以 MySQL DATE 格式存储您的日期并使用以下查询:

SELECT 
        * 
    FROM 
        table 
    WHERE 
        MONTH(date_field) = MONTH(CURRENT_DATE) 
    AND 
        YEAR(date_field) = YEAR(CURRENT_DATE)

Storing dates as a string/varchar is a very bad idea.

将日期存储为字符串/varchar 是一个非常糟糕的主意。

回答by Zagor23

SELECT * FROM `your_table` WHERE MONTH(`your_date_column`)=6 
AND YEAR(`your_date_column`)=2012

Gets everything from June 2012.

获取 2012 年 6 月的所有内容。