实施LIMIT和OFFSET时出现语法错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实施LIMIT和OFFSET时出现语法错误相关的知识,希望对你有一定的参考价值。
通过执行php
上的SQL
,我跟随了MARIADB
为我提供数据。
function getData ($countsql, $datasql, $page, $limit, $input, $response){
try{
$offset = ($page-1) * $limit; //calculate what data you want
$db = new db();
$db = $db->connect();
$countQuery = $db->prepare( $countsql );
$dataQuery = $db->prepare( $datasql );
$dataQuery->bindParam(':limit', $limit, PDO::PARAM_INT);
$dataQuery->bindParam(':offset', $offset, PDO::PARAM_INT);
while(sizeof($input)){
$curr = array_pop($input);
$dataQuery->bindParam($curr["key"], $curr["keyvalue"]);
$countQuery->bindParam($curr["key"], $curr["keyvalue"]);
}
echo $datasql."+";
echo $limit."+";
echo $offset;
$dataQuery->execute();
$countQuery->execute();
$db = null; // clear db object
$count = $countQuery->fetch(PDO::FETCH_ASSOC);
$data = $dataQuery->fetchAll(PDO::FETCH_ASSOC);
if($count['COUNT']>0&&count($data)){
$data_arr=array();
$data_arr["records"]=array();
$data_arr["pagination"]=array();
$data_arr["records"] = $data;
$data_arr["pagination"] = array(
"count" => (int)$count['COUNT'],
"page" => $page,
"limit" => $limit,
"totalpages" => ceil($count['COUNT']/$limit)
);
return $response->withJson($data_arr,200);
}
else{
return $response->withJson (
array("msg" => "Nothing found."),
204
);
}
}catch( PDOException $e ) {
//return '{"error": {"msg":' . $e->getMessage() . '}';
return $response->withJson (
array("msg" => $e->getMessage()),
500
);
}
}
问题是当我在本地MARIADB
服务器上执行此操作时,代码工作正常,但是当我在联机服务器上执行此操作时,它会产生以下错误(请注意,我在最后打印了SQL + limit + offset调试)
{"msg":"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 ''999999' OFFSET 0' at line 1"}SELECT * , (SELECT COUNT(*) FROM ART WHERE ART.AUTHOR_ID = AUTHOR.ID) as COUNT FROM AUTHOR LIMIT :limit OFFSET :offset+999999+0
语法或版本不匹配是否存在错误?
编辑
我也想问一件事,
这是获得COUNT个的正确方法
SELECT * , (SELECT COUNT(*) FROM ART WHERE ART.AUTHOR_ID = AUTHOR.ID) as COUNT FROM AUTHOR
或者我应该加入这两个表,然后计算相同的表吗?
答案
我不知道足够的PHP来回答您问题的第一部分,但这是我将使用的原始mysql查询:
SELECT
AU.*,
COALESCE(AR.CNT, 0) AS COUNT
FROM AUTHOR AU
LEFT JOIN
(
SELECT AUTHOR_ID, COUNT(*) AS CNT
FROM ART
GROUP BY AUTHOR_ID
) AR
ON AU.ID = AR.AUTHOR_ID;
以上是关于实施LIMIT和OFFSET时出现语法错误的主要内容,如果未能解决你的问题,请参考以下文章
在 Doctrine2 查询中使用 Limit 和 Offset
在片段java类中使用“this”和getLastSignedInAccount时出现错误[重复]
分析 GPX 数据时出现错误“'NoneType' 对象没有属性 'offset'”