Mysql查询使用从现在到上周的日期

时间:2018-01-26 11:28:59

标签: php mysql sql mysqli between

所以我试图从今天和7天前的数据库中获取结果,但我正在做的事情似乎是错误的,因为我一直收到致命的错误

  

未捕获的异常' mysqli_sql_exception'带有消息'您的SQL语法中有错误;检查与您的MariaDB服务器版本对应的手册,以获得正确的语法,以便在“日期”下使用“DAYS GROUP BY logins.unique_id ORDER BY'堆栈跟踪:#0 mysqli->查询(' SELECT SUM(DIST ...',1)#1 {main}抛出

  <?php //get info for scores in the league
             if ($result = $link->query("SELECT SUM(DISTINCT step_count.steps) as total,  logins.nickname, MAX(step_count.steps) as maxsteps, ROUND(AVG (DISTINCT step_count.steps)) as average, logins.Email as email
                FROM step_count
                INNER JOIN logins on
                  step_count.unique_id=logins.unique_id
              WHERE logins.unique_id='$unique_id' AND step_count.date BETWEEN CURDATE() AND CURDATE() + INTERVAL 7 DAYS
                GROUP BY logins.unique_id
                ORDER BY `total` DESC
              ", MYSQLI_USE_RESULT))

              while($row = $result->fetch_assoc()){ ?>

更新列后,我仍然收到同样的致命错误

2 个答案:

答案 0 :(得分:2)

此处存在语法问题,您在BETWEEN

之前缺少一列
logins.unique_id='$unique_id' BETWEEN CURDATE() AND CURDATE() + INTERVAL 7 DAYS

BETWEEN的正确语法是

<column_name> BETWEEN <value1> AND <value2>

所以,应该是

logins.unique_id='$unique_id' AND <date_column> BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) 

并使用DATE_ADD代替添加特定天数。

答案 1 :(得分:0)

同样要收到今天和7天之前的数据,您需要使用DATE_SUB,以便查询的最后部分为:

step_count.date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()

您的GROUP BY应该是:

GROUP BY logins.nickname, email