MySQL only within the current month?

你说的曾经没有我的故事 提交于 2019-11-30 18:46:57
ajreal

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')
Anax

You need to limit the results by using YEAR() and MONTH() functions. Change the WHERE part of your query like this:

WHERE t1.website != ''
AND YEAR(time) = YEAR(NOW())
AND MONTH(time) = MONTH(NOW())

This is probably a lot more straightforward than you are going to expect.

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 != ''
       AND t2.time >= DATE_SUB( CURRENT_DATE, INTERVAL 1 DAY )
GROUP  BY t1.username,
          t1.website
ORDER  BY in_count DESC 
LIMIT  0, 10 
where t2.time >= extract(YEAR_MONTH from CURRENT_DATE) 
  and t2.time <  extract(YEAR_MONTH from CURRENT_DATE + INTERVAL 1 MONTH)

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.

For better performances (--> use index), create an index on your date column and user a "between" in your where clause.

select ... from my_table where my:date_field between concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01')
and adddate(concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01'), interval 1 month);

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.

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