Mysql查询发布日期减去7天

时间:2013-03-02 19:13:43

标签: mysql sql yii

这不断出现错误,我无法弄清楚为什么......

SELECT
  i.user_id
FROM (SELECT
    SUM(us.score) AS score_sum,
    us.user_id
      FROM user_scores us
      WHERE us.created >= DATE(DATE_SUB(NOW(),INTERVAL 7 DAY))
      GROUP BY us.user_id) AS i
ORDER BY i.score_sum
LIMIT 1

带有消息

的异常'CDbException'
  

CDbCommand无法执行SQL语句:CDbCommand无法准备SQL语句:SQLSTATE [HY000]:常规错误:1接近“7”:语法错误。

执行的SQL语句是:

SELECT
  i.user_id
FROM (SELECT
    SUM(us.score) AS score_sum,
    us.user_id
      FROM user_scores us
      WHERE us.created >= DATE(DATE_SUB(NOW(),INTERVAL 7 DAY))
      GROUP BY us.user_id) AS i
ORDER BY i.score_sum
LIMIT 1



<?php

class WinnerCommand extends CConsoleCommand
{
    public function actionSelect()
    {
        $sql = "SELECT i.user_id FROM
            (SELECT SUM(us.score) AS score_sum, us.user_id FROM user_scores us
            WHERE us.created >= DATE(DATE_SUB(NOW(),INTERVAL 7 DAY))
            GROUP BY us.user_id) AS i
            ORDER BY i.score_sum
            LIMIT 1";
        $user_id = Yii::app()->db->createCommand($sql)->queryScalar();
        echo $user_id;
        return $user_id;
    }

}

&GT;

1 个答案:

答案 0 :(得分:3)

我无法解释问题,但您可以消除表达式中的子查询。也许这会有所帮助:

        SELECT us.user_id
        FROM user_scores us
        WHERE us.created >= DATE(DATE_SUB(NOW(), INTERVAL 7 DAY))
        GROUP BY us.user_id)
        ORDER BY SUM(us.score)
        LIMIT 1