0

I am trying to get all rows from a database that was added between 5 and 10 minutes ago.

Here is what I have tried:

$query9 = mysql_query("SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 5 minute) AND date_sub(now(), interval 10 minute);"); 

$onlineUsersLast10Mins = mysql_num_rows($query9);

Despite having data in the database from 6,7,8 and 9 mins ago, this script is not picking it up. Where am I going wrong?

for info, dates are stored as a timestamp in the usual format yyyy-mm-dd hh:mm:ss

4
  • It seems that the left side of your between interval is greater than the right side. If you swap them , is this working well? Commented Sep 15, 2016 at 13:27
  • Sorry what do you mean Commented Sep 15, 2016 at 13:27
  • I will write an answer where I try to clarify your problem and explain the solution. Bear with me :) Commented Sep 15, 2016 at 13:28
  • Sure, you are welcome :) Commented Sep 15, 2016 at 14:01

2 Answers 2

1

The semicolon at the end of your query BEFORE the last double quote needs to be removed:

$query9 = mysql_query("SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 10 minute) AND date_sub(now(), interval 5 minute)"); 

This should work.

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

2 Comments

Hi, unfortunately that hasn't made a difference...?
Hi, made an edit, also your interval needs to have the date that is further back in time first ---> see here stackoverflow.com/questions/9926147/…
0

Let's take a look at BETWEEN's documentation.

BETWEEN works with an interval, but if you take a look at this official example:

mysql> SELECT 2 BETWEEN 1 AND 3, 2 BETWEEN 3 and 1;

-> 1, 0

you will see that 2 is between 1 and 3, but 2 is not between 3 and 1. So, if the right side is bigger than the left side, like in the second case where 3 is the left and 1 is the right, then your element will not be between them.

So, 2 is between 1 and 3, but 2 is not between 3 and 1.

Let us take a look at your query:

SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 5 minute) AND date_sub(now(), interval 10 minute);

The left side contains the moment earlier than now with 5 minutes and the right side contains the moment earlier than now with 10 minutes. So, the right side is actually earlier (smaller) than the left side. We need to see whether we have values between 10 minutes ago and 5 minutes ago, not the other way around :)

So, this should be the query:

SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 10 minute) AND date_sub(now(), interval 5 minute);

Comments

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.