如何在MySQL中按月获取记录?

I have stored Date in database in dd-mm-yy format, for example 03-10-2013,

How to search record by month? Month in digit (01 to 12);

I am using currently

$query = "SELECT * FROM data  WHERE date LIKE %$month%";

but this not working properly.

Fix the date format in your database structure first, change it to: yyyy-mm-dd

Then change your query statement to:

$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';

This will select the month as '5' or '11' or '12' which will give duplicates for differing years.

If you need the month with year (to avoid duplicate years):

$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);

This will return: '2015-01' or '2014-12'

To get date as '01' or '04' or '12':

$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);

Try this...

You could use MySQL MONTH() function

MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0

4 is april

SELECT * FROM tbl WHERE MONTH( date ) ='4' 

You can do like it... as it is not in date format(YYYY-MM-DD)

$q="SELECT * FROM data  WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";

I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.

Based on that there are few ways to do this.

  1. Leave the database as it is and convert values on the fly.

SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;

  1. Change the type of the column to a "date" type column

SELECT * FROM data WHERE Month(realdatecolumn) = 5;

  1. Change the type of the column to a "date" type column, store a separate column for the month.

UPDATE data set monthcolumn = Month(realdatetimecolumn)

then

SELECT * FROM data WHERE monthcolumn = 5;

Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data