语法错误或访问冲突

时间:2015-07-21 16:05:14

标签: php mysql sql

以下SQL在phpmyadmin中执行时有意为,但是当我尝试在我的PHP脚本中执行它会引发异常。

$log_stats = DB::select(DB::raw("
        SET @startDate = '$from';
        SET @endDate = '$db_to';
        SET @total_duration = (CAST(@endDate as DATETIME) - CAST(@startDate as DATETIME)); 

        SELECT t1.status
            ,SUM(IF(t2.cron_ran_at IS NULL OR t2.cron_ran_at > @endDate,
            CAST(@endDate AS DATETIME),
            t2.cron_ran_at) -
        IF(t1.cron_ran_at < @startDate,
           CAST(@startDate AS DATETIME),
            t1.cron_ran_at)) / @total_duration as duration
        FROM monitor_logs t1
        LEFT JOIN monitor_logs t2 ON t1.id = (t2.id - 1)
        WHERE (t2.cron_ran_at > @startDate OR t2.cron_ran_at IS NULL) AND t1.cron_ran_at < @endDate
        GROUP BY t1.status
"));

抛出异常......

  

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在&#39; SET @endDate =&#39; 2015-07-22 00:00:00&#39 ;;附近使用正确的语法。 SET @total_duration =(CAST(@endDate&#39;第2行(SQL:SET @startDate =&#39; 2015-07-14 00:00:00&#39 ;; SET @endDate =&#39; 2015 -07-22 00:00:00&#39 ;; SET @total_duration =(CAST(@ endDate as DATETIME) - CAST(@startDate as DATETIME)); SELECT t1.status,SUM(IF(t2.cron_ran_at IS NULL OR) t2.cron_ran_at&gt; @endDate,CAST(@ endDate AS DATETIME),t2.cron_ran_at) - IF(t1.cron_ran_at&lt; @startDate,CAST(@startDate AS DATETIME),t1.cron_ran_at))/ @total_duration as duration FROM monitor_logs t1 LEFT JOIN monitor_logs t2 ON t1.id =(t2.id - 1)WHERE(t2.cron_ran_at&gt; @startDate OR t2.cron_ran_at IS NULL)AND t1.cron_ran_at&lt; @endDate GROUP BY t1.status)`< / p>

1 个答案:

答案 0 :(得分:1)

您无法在PHP中的一个查询中运行多个mysql语句。您应该将其设为存储过程或函数。