我正在尝试在存储过程中执行prepared语句。
但我对此有意见。
以下是存储过程:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getAllUserLunchReport`(IN `start_date` DATETIME, IN `end_date` DATETIME)
BEGIN
SET GLOBAL group_concat_max_len=4294967295;
SET @SQL = NULL;
SET @start_date = DATE(start_date);
SET @end_date = DATE(end_date);
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN date = "',DATE(issuedDateTime),'" THEN lunchStatus ELSE 0 END) AS `',DATE(issuedDateTime),'`'
)
) INTO @SQL
FROM `lunch_status`
WHERE DATE(issuedDateTime) BETWEEN @start_date AND @end_date;
SET @SQL
= CONCAT('SELECT userId, ', @SQL, '
FROM
(
SELECT userId, lunchStatus, DATE(issuedDateTime) as date
FROM `lunch_status`
WHERE DATE(issuedDateTime) BETWEEN "',@start_date,'" AND "',@end_date,'"
) as a
GROUP BY userId;');
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
下面是错误:
PDOStatement: 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 'NULL' at line 1
这是控制器:
public function weeklyLunchReport($date1=null, $date2=null)
{
$user = AclHelper::getCurrentUser();
$default_userID = intval($user['user_id']);
$defDate = new DateTime();
$default_date = $defDate->format('Y-m-d');
$date1 = (isset($date1) && $date1 != '') ? $date1 : $default_date;
$date2 = (isset($date2) && $date2 != '') ? $date2 : $default_date;
$records = $this->db->exec("CALL getAllUserLunchReport ('$date1','$date2')");
return $records;
}
另外:下面是sql变量的值:
SELECT userId,
SUM(CASE WHEN date = "2018-06-03" THEN lunchStatus ELSE 0 END) AS `2018-06-03`,
SUM(CASE WHEN date = "2018-06-04" THEN lunchStatus ELSE 0 END) AS `2018-06-04`,
SUM(CASE WHEN date = "2018-06-06" THEN lunchStatus ELSE 0 END) AS `2018-06-06`,
SUM(CASE WHEN date = "2018-06-07" THEN lunchStatus ELSE 0 END) AS `2018-06-07`,
SUM(CASE WHEN date = "2018-06-08" THEN lunchStatus ELSE 0 END) AS `2018-06-08`
FROM
(
SELECT userId, lunchStatus, DATE(issuedDateTime) as date
FROM `lunch_status`
WHERE DATE(issuedDateTime) BETWEEN "2018-06-03" AND "2018-06-09"
) as a
GROUP BY userId;
单独运行此查询字符串将得到预期的结果集。
这个问题看起来很好,但我不知道哪里出了问题。
非常感谢您的帮助。提前谢谢。
1条答案
按热度按时间8zzbczxx1#
我在mysql客户机中尝试了您的过程,为了排除任何与php相关的问题:
但是当我尝试插入一行属于日期范围时:
问题是你的
GROUP_CONCAT()
如果要搜索的日期范围中没有行,则为透视表列列表生成null。然后将该空值合并到完整的select语句中,但是
CONCAT('SELECT ...', NULL, 'FROM ...')
产生null,因为将任何字符串与null连接会产生null。你需要确保你的
GROUP_CONCAT()
默认为一些非空字符串:调用该过程仍然不会返回任何结果集,因为表中没有与您给定的日期范围匹配的日期。但至少在准备null时不会出现语法错误。