0

I Have fetched records from two tables using the query given below.

mysql_query("SELECT Table1.username, SUM(Table2.points) 
AS total FROM Table2 INNER JOIN Table1 ON Table1.userid = Table2.userid 
GROUP BY Table1.username ORDER BY SUM(Table2.points) DESC LIMIT 10");

I am trying to fetch the same recrods with date/time limits[1 day ] 2nd case [7 days days].

mysql_query("SELECT Table1.username, SUM(Table2.points) 
AS total FROM Table2  WHERE  Table2.date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW() 
INNER JOIN Table1 ON Table1.userid = Table2.userid 
        GROUP BY Table1.username ORDER BY SUM(Table2.points) DESC LIMIT 10");

This query is not working , i cant find the problem with this query.

Table1 does not conatin any date colomn.
Table2 contain one date coloumn that i want to use for time intervals.

I have tried all the below given queires. and receiving the same error for all.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

Addition: I am using Timestamp in date type.

Kindly guide.

2 Answers2

1

not only is the where in the wrong place it looks like you should use CURDATE() instead of NOW() since you said it was a date column and not a datetime column

SELECT t1.username, SUM(t2.points) AS total 
FROM Table2 t2
JOIN Table1 t1 ON t1.userid = t2.userid  
WHERE t2.date BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE()     
GROUP BY t1.username 
ORDER BY total DESC 
LIMIT 10;

NOTE: mysql_* is deprecated and you shouldn't use it... you should switch over to PDO or mysqli using a parameterized query..

read about parameterization here as well as a good way to prevent sql injection incase you ever need to pass in variables

YOUR QUERY

SELECT Table1.username, SUM(Table2.points) AS total 
FROM Table2  
WHERE  Table2.date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW() 
^------------------------------------------------------------^ = bad this should be your JOIN first and then WHERE
INNER JOIN Table1 ON Table1.userid = Table2.userid 
GROUP BY Table1.username 
ORDER BY SUM(Table2.points) DESC LIMIT 10

MY QUERY

SELECT t1.username, SUM(t2.points) AS total 
FROM Table2 t2
JOIN Table1 t1 ON t1.userid = t2.userid  
WHERE t2.date BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE()     
GROUP BY t1.username 
ORDER BY total DESC 
LIMIT 10;

notice the WHERE goes after JOIN but before GROUP BY...

Community
  • 1
  • 1
John Ruddell
  • 24,127
  • 5
  • 51
  • 83
0

Hello as the sum should be applied on the interval, use having instead of where.

SELECT Table1.username, SUM(Table2.points) AS total 
  FROM Table2  
 INNER JOIN Table1 ON Table1.userid = Table2.userid 
 GROUP BY Table1.username 
 HAVING   Table2.date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW()
 ORDER BY SUM(Table2.points) DESC LIMIT 10