how do I get month from date in mysql

青春壹個敷衍的年華 提交于 2019-11-27 14:19:03

You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):

SELECT * 
  FROM table 
 WHERE amount > 1000 
   AND MONTH(dateStart) = {$m}

Caveats:


Alternatives:


Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:

WHERE startdate BETWEEN STR_TO_DATE([start_date], [format]) 
                    AND STR_TO_DATE([end_date], [format])

See the documentation for formatting syntax.

Reference:


Use the month() function.

select month(now());

Try this:

SELECT * 
FROM table 
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')

E.g.

$date = sprintf("'%04d-%02d-01'", $year, $month);
$query = "
  SELECT
    x,y,dateStart
  FROM
    tablename
  WHERE
    AND amount > 1000
    AND dateStart >= $date
    AND dateStart < $date+Interval 1 month
";
mysql_query($query, ...

This will create a query like e.g.

WHERE
  AND amount > 1000
  AND dateStart >= '2010-01-01'
  AND dateStart < '2010-01-01'+Interval 1 month

+ Interval 1 month is an alternative to date_add().

SELECT Date('2010-01-01'+Interval 1 month)-> 2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)-> 2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.

Try this

SELECT * 
      FROM table 
     WHERE amount > 1000 
       AND MONTH(datestart)
    GROUP BY EXTRACT(YEAR_MONTH FROM datestart)

Try this if(date field is text then convert this string to date):

SELECT * FROM `table_name` WHERE MONTH(STR_TO_DATE(date,'%d/%m/%Y'))='11'

//This will give month number MONTH(STR_TO_DATE(date,'%d/%m/%Y'))
//If its return 11 then its November
// Change date format with your date string format  %d/%m/%Y
Mr.DIpak SOnar

Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

  • Day:

    SELECT EXTRACT(DAY FROM "2017-06-15");
    
  • Month:

    SELECT EXTRACT(MONTH FROM "2017-06-15");
    
  • Year:

    SELECT EXTRACT(YEAR FROM "2017-06-15");
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!