Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL only within the current month?

I have the following MySQL query, and I'm trying to adjust it so it only fetches results which are within the current month (of the current year), I'm guessing you may require more info about my MySQL structure so here it goes - I have a UNIX timestamp generated by PHP's time() stored within the time column (under the referrals table), so with the below setup it would be t2.time.

So my problem is I'm unsure how to proceed, I'm guessing it would be something like adding the following to end of the WHERE clause? => AND t2.time IS WITHIN THE CURRENT MONTH (caps are just on to distinguish problem from rest of query) but i'm not sure how to check if its within the current month.

The MySQL Query:

SELECT t1.username,
       t1.website,
       SUM(IF(t2.type = 'in', 1, 0))  AS in_count,
       SUM(IF(t2.type = 'out', 1, 0)) AS out_count
FROM   users AS t1
       JOIN referrals AS t2
         ON t1.username = t2.author
WHERE  t1.website != ''
GROUP  BY t1.username,
          t1.website
ORDER  BY in_count DESC 
LIMIT  0, 10 

Appreciate all help! :B

like image 973
newbtophp Avatar asked Jan 11 '11 06:01

newbtophp


People also ask

How do I get current month data in SQL?

We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.

What does NOW () do in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS.

How do I get Currentdate in MySQL?

Simply use the CURDATE() function to get the current date. The date can be displayed in two different formats: ' YYYY-MM-DD ' if it is used in a string context or YYYYMMDD if it is used in a numeric context. There are two other functions that can be used instead of CURDATE() : CURRENT_DATE and CURRENT_DATE() .

How do you get the month from a timestamp field?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column.


1 Answers

you can use from_unixtime like

date_format(from_unixtime(t2.`time`), '%Y-%m')=date_format(now(), '%Y-%m')

But I think data type integer is not so suitable for this requirement

I would think using datetime will be more suitable, built an index on this column and this also make the filtering easier, like

t2.`time`>='2011-01-01' and t2.`time`<'2011-02-01'

or

date_format(t2.`time`, '%Y-%m')=date_format(now(), '%Y-%m')
like image 150
ajreal Avatar answered Oct 30 '22 15:10

ajreal