以下 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]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @endDate = '2015-07-22 00:00:00'; SET @total_duration = (CAST(@endDate ' at line 2 (SQL: SET @startDate = '2015-07-14 00:00:00'; SET @endDate = '2015-07-22 00:00:00'; 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 )`
最佳答案
您不能在 PHP 的一个查询中运行多个 mysql 语句。您应该将其设为存储过程或函数。
关于php - 语法错误或访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31544158/