0

Before i used datetime for post created time from database,

SELECT MONTH(created)+1, count(*) 
FROM post_comments
WHERE YEAR(created) = YEAR(CURDATE())
group by MONTH(created)
ORDER BY MONTH(created)

and now i am using unix timestamp. How I need to make a change in the above code, to work it unix timestamp.

Before the created time looks like this: 2018-04-28 09:03:02

and now the created time looks like this: 1524921263

1
  • Do you want to format it sql side or php side Commented Apr 28, 2018 at 13:19

1 Answer 1

1

You can convert everything to dates using FROM_UNIXTIME():

SELECT MONTH(FROM_UNIXTIME(created))+1, count(*) 
FROM post_comments
WHERE YEAR(FROM_UNIXTIME(created)) = YEAR(CURDATE())
GROUP BY MONTH(FROM_UNIXTIME(created))
ORDER BY MONTH(FROM_UNIXTIME(created));

I find it odd that you are adding 1 to the month in the SELECT.

You can change the WHERE to:

WHERE created >= UNIX_TIMESTAMP(DATE(CONCAT(YEAR(CURDATE), '-01-01')))

In general, it is a good idea to avoid the use of functions on columns. This is less important when you are selecting a significant number of rows (unless the column is a clustered index).

Sign up to request clarification or add additional context in comments.

4 Comments

You better of using the Unix time stamp for the where if there’s any significant amount of data vs a subfunction
@gordonlinoff the WHERE created without YEAR(FROM_UNIXTIME(created)) ?
I mean, using a function to cast every value in the table as a year, and then comparing the result vs, doing a between jan 1 and dec 31 on that year, but just leaving the range in timestamp format for the sake of comparing INTS and\or using an index. Search first, group later
@Azzo . . . Yes, as in the last example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.