2014-10-16 99 views
0

我已經使用下面給出的查詢從兩個表中提取記錄。錯誤是查詢連接和日期/時間間隔

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"); 

我試圖獲取與日期/時間限制[1天]第二種情況[7天天]相同的recrods。

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"); 

此查詢不起作用,我無法找到此查詢的問題。

表1不贊成任何日期colomn。
表2包含一個我想用於時間間隔的日期顏色。

我已經嘗試了下面給出的所有queires。併爲所有人接收相同的錯誤。

警告:mysql_fetch_array()預計參數1是資源,布爾在

加成給出:我在日期類型使用時間戳。

請指導。

+2

嘗試移動'WHERE'條件後的'INNER JOIN/ON'語句,就在「GROUP BY」之前。 – 2014-10-16 16:29:49

+0

也不起作用。並出現相同的錯誤 – 2014-10-16 16:36:07

+0

錯誤說明了什麼?將問題添加到問題中可能是一個好主意。 – 2014-10-16 16:37:12

回答

1

不僅是在錯誤的地方,它看起來像你應該使用CURDATE()的地方,而不是NOW(),因爲你說,這是一個日期列,而不是日期時間列

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; 

注: mysql_ *已被棄用,你不應該使用它...你應該切換到PDO或使用參數化查詢的mysqli ..

瞭解參數here as well as a good way to prevent sql injection incase you ever need to pass in variables

您的查詢

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 

我的查詢

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; 

通知WHERE那張JOIN之後,但GROUP BY之前...

+0

的問題,更新了錯誤 – 2014-10-16 19:12:56

+0

@AtifShabbir這個問題,這意味着你的查詢失敗並且返回FALSE而不是fetch_array()的資源...所以試試我的查詢。 ..告訴我,如果它仍然是這樣的錯誤 – 2014-10-16 19:14:52

+0

@AtifShabbir看到[** HERE **](http://stackoverflow.com/a/2973209/2733506) – 2014-10-16 19:27:41

0

你好,因爲總和應該在間隔上應用,所以使用而不是在哪裏。

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 
+0

的問題,更新了錯誤 – 2014-10-16 19:05:49