我使用下面给出的查询从两个表中获取了记录。
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天]第2个案例[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包含一个我希望用于时间间隔的日期颜色。
我已经尝试了以下所有给出的队列。并为所有人收到同样的错误。
警告:mysql_fetch_array()期望参数1是资源,布尔值在
中给出补充:我在日期类型中使用时间戳。
请指导。
答案 0 :(得分: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之前...
答案 1 :(得分: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