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
This is probably a lot more straightforward than you are going to expect.
You need to limit the results by using
YEAR()
andMONTH()
functions. Change theWHERE
part of your query like this:This assume t2.time is a datetime type. If its an integer unix timestamp, you can convert the upper and lower datetime boundaries we created, by using the UNIX_TIMESTAMP() function.
you can use
from_unixtime
likeBut I think data type
integer
is not so suitable for this requirementI would think using
datetime
will be more suitable, built an index on this column and this also make the filtering easier, likeor
For better performances (--> use index), create an index on your date column and user a "between" in your where clause.
Check this MONTH function in MySql.
You can add condition like
MONTH( FROM_UNIXTIME( t2.time ) ) = Month(NOW())
Edited after getting help in comments from fireeyedboy.