使用DB :: select执行查询的Laravel 5问题

时间:2016-10-13 13:47:52

标签: php mysql laravel laravel-5 laravel-5.2

我的查询在phpmyadmin sql中完全有效,但是当我尝试在laravel 5 DB::select中运行查询时,它给出了一个错误:代码:

public function getCheckDueCurrentMonth()
    {
        $query = "SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) GROUP BY  SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC";

        $results = DB::select( DB::raw($query)); 
        return $results;


    }

这是错误:

QueryException in Connection.php line 761:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL 
 syntax; 
check the manual that corresponds to your MariaDB server version for the right syntax to 
use near 
'WHERE MAX(HISTORY_ID) GROUP BY SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC)' 
at line 1 (SQL: (SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN NOW() 
AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) 
GROUP BY SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC))

3 个答案:

答案 0 :(得分:0)

使用此

public function getCheckDueCurrentMonth()
        {
            $query = "SELECT * FROM history_card WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE MAX(HISTORY_ID) GROUP BY  SERIAL_NUMBER ORDER BY DUE_CAP_CHECK_DATE DESC";

            $results = DB::Raw($query); 
            return $results;


        }

答案 1 :(得分:0)

首先,您的查询错误。正如我在评论中提到的,查询只能有1个WHERE。使用AND或OR加入多个子句。

$query = "SELECT * FROM history_card 
    WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)     
    AND MAX(HISTORY_ID) 
    GROUP BY  SERIAL_NUMBER 
    ORDER BY DUE_CAP_CHECK_DATE DESC";

我猜你只想要最后一个history_id,所以你需要将它添加到比较中:

$query = "SELECT * FROM history_card 
    WHERE DUE_CAP_CHECK_DATE BETWEEN  NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) 
    AND history_id = MAX(HISTORY_ID) 
    GROUP BY  SERIAL_NUMBER 
    ORDER BY DUE_CAP_CHECK_DATE DESC";

DB :: raw通常是在您使用DB::select()->where()....进行列比较或MySQL函数时,因此您可以将其放在此处。

$results = DB::select( $query);

答案 2 :(得分:0)

事实证明,laravel 5使用严格模式'在MySQL中,如果要禁用它,请转到MySQL中的database.php查找'strict' => true并将其转为'strict' => false