Search code examples
mysqlsqlgroup-byunix-timestamp

How to fetch last 24 hour record using unix timestamps


I have following two tables in MySQL and I want to get name and count of reviews. How can I do this?

Here is my table un_users:

id      wallet_address          username    
1       xxxxxxxxxxxxxx          abc
2       xxxxxxxxxxxxxx          xyz
3       xxxxxxxxxxxxxx          def
4       xxxxxxxxxxxxxx          jkl 

Here is my table coin_review:

id      wallet_address      review                  review_creation_time
1       xxxxxxxxxxxxx       Lorem Ipsum1            1632812650  
2       xxxxxxxxxxxxx       Lorem Ipsum2            1632812211
3       xxxxxxxxxxxxx       Lorem Ipsum3            1632812650
4       xxxxxxxxxxxxx       Lorem Ipsum4            1632814574

I tried with following code but not working:

SELECT u.username, COUNT(c.Review) AS totalreview
FROM un_users u
LEFT JOIN coin_review c ON c.wallet_address = u.wallet_address
GROUP BY u.username
ORDER BY u.username

I want to know how can I get "last 24 hours" records?


Solution

  • Assuming that review_creation_time is a unix timestamp, you can use UNIX_TIMESTAMP() function to compare apples to apples:

    SELECT
        u.id, u.wallet_address, u.username,
        COUNT(c.id) AS review_count
    FROM un_users u
    JOIN coin_review c ON c.wallet_address = u.wallet_address
    WHERE c.review_creation_time >  UNIX_TIMESTAMP(CURRENT_TIMESTAMP - INTERVAL 24 HOUR)
    AND   c.review_creation_time <= UNIX_TIMESTAMP()
    GROUP BY u.id