views:

309

answers:

4

I want to be able to fetch results from mysql with a statement like this:

SELECT * 
  FROM table 
 WHERE amount > 1000 

But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:

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

...$m being a month but it gave error.

In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?

A: 

Use the month() function.

select month(now());
Gattster
I didn't downvote you, but the answer as-is provides next to no help give the question.
OMG Ponies
+1  A: 

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.

VolkerK
A: 

Try this:

SELECT * 
FROM table 
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')
Louis
+1  A: 

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:


OMG Ponies