在一切之前,抱歉我的英语不好。
我有这个问题:
SELECT t1.*,(SELECT COUNT(*) FROM table_a t2 WHERE t1.id=t2.id_c AND t2.status=1) AS aula
FROM table_c t1
WHERE t1.status=1
AND t1.id IN (SELECT t3.id_c FROM table_cu t3 WHERE t3.id_c=t1.id AND t3.id_u=1)
AND t1.id IN (SELECT t4.id_c FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3)
LIMIT 0,25
这个查询返回给我一组结果,直到现在都没有问题,但我有一个非常基本的进程的分页类:它计算我得到了多少条目,然后它将条目分成几部分,然后用这个值我分页。
问题出在这个方法的分页类中,这里的代码是:
function total_entries()
{
$db = new db(DB_USER, DB_PASS, DB_NAME, DB_HOST);
$qtdEntries = 0;
$queryQtd = $this->sql;
$queryQtd = preg_replace("/SELECT (.*) FROM /sei", "'SELECT COUNT(*) as qtd FROM '", $queryQtd);
$queryQtd = preg_replace("/ORDER BY (.+)/", "", $queryQtd);
$queryQtd = preg_replace("/LIMIT (.+)/", "", $queryQtd);
$resultAll = $db->get_row($queryQtd); //Gets the result, in this case, it returns the number of entries
if($resultAll){
$qtdEntries = $resultAll->entries; //Number of entries
}
return $qtdEntries;
}
基本上当我运行这个方法时,它内部的查询返回如下:
SELECT COUNT(*) as qtd FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3)
什么时候应该返回这样的东西:
SELECT COUNT(*) as qtd FROM table_c t1 WHERE t1.status=1
有任何想法如何纠正这个问题?
答案 0 :(得分:2)
解决此问题的更好方法是使用MySQL内置功能:
您只需在SELECT
关键字与SQL_CALC_FOUND_ROWS函数结合后添加FOUND_ROWS:
SELECT SQL_CALC_FOUND_ROWS t1.*,(SELECT COUNT(*) FROM table_a t2 WHERE t1.id=t2.id_c AND t2.status=1) AS aula
FROM table_c t1
WHERE t1.status=1
AND t1.id IN (SELECT t3.id_c FROM table_cu t3 WHERE t3.id_c=t1.id AND t3.id_u=1)
AND t1.id IN (SELECT t4.id_c FROM table_cp t4 WHERE t4.id_c=t1.id AND t4.id_p=3)
LIMIT 0,25
如果没有LIMIT
子句,要获取行数,现在可以使用语句
SELECT FOUND_ROWS();
作为下一个查询。
正则表达式方法的问题是使正则表达式正确。匹配通常是贪婪的,它会尽可能地匹配。在这种情况下,它将恰好匹配WHERE
子句的最后一个条件,因为此条件使用带有FROM
关键字的子选择。因为那个模式
SELECT (.*) FROM
在
$queryQtd = preg_replace("/SELECT (.*) FROM /sei", "'SELECT COUNT(*) as qtd FROM '", $queryQtd);
比SELECT的字段列表(包含带FROM
的子选项)的匹配要多得多。