由于 Codeigniter(恕我直言)中的分页在使用过滤器(开头字母、类别等)时缺少一些便于实施的好东西,即使我的分页功能齐全且正常工作 - 我有两个查询正在运行,它们之间的唯一区别是其中一个在末尾有 LIMIT (和 OFFSET)。需要第二个查询,因为我必须获取总行数,而我的“主”查询我无法得到它,因为它有 LIMIT,所以它返回有限的行数。
QUERY 1(“主要”查询)
SELECT art.*, songs.numsongs
FROM _tbl_artists AS art
LEFT JOIN
(SELECT _ARTIST_ID, COUNT(*) AS numsongs
FROM _tbl_songs GROUP BY _ARTIST_ID) AS songs
ON art._ID_ORIGINAL = songs._ARTIST_ID
WHERE art._artist_type = 0 AND art._ARTIST_NAME LIKE 'C%' AND art.id > 0 ORDER BY art._ARTIST_NAME ASC LIMIT 20, 20
QUERY 2(这个计算行数)
SELECT art.*, songs.numsongs
FROM _tbl_artists AS art
LEFT JOIN
(SELECT _ARTIST_ID, COUNT(*) AS numsongs
FROM _tbl_songs GROUP BY _ARTIST_ID) AS songs
ON art._ID_ORIGINAL = songs._ARTIST_ID
WHERE art._artist_type = 0 AND art._ARTIST_NAME LIKE 'C%' AND art.id > 0 ORDER BY art._ARTIST_NAME ASC
模型代码(它很乱,我知道:)):
function loadArtists($type='', $letter='', $uriOffset=0, $perPage='')
{
$letterEval = preg_match('[0-9]', $letter);
switch($letterEval):
case 1:
$operator = 'REGEXP';
$letter = "^[0-9]";
$s = '';
break;
case 0:
$operator = 'LIKE';
$letter = "$letter";
$s = '%';
break;
default: 0; break;
endswitch;
$query = "SELECT SQL_CALC_FOUND_ROWS art.*, songs.numsongs
FROM _tbl_artists AS art
LEFT JOIN
(SELECT _ARTIST_ID, COUNT(*) AS numsongs
FROM _tbl_songs GROUP BY _ARTIST_ID) AS songs
ON art._ID_ORIGINAL = songs._ARTIST_ID
WHERE";
if($type == 0 || $type == 1)
$query .= " art._artist_type = $type AND";
if($letter != '')
$query .= " art._ARTIST_NAME $operator '$letter$s' AND";
else
$query .= '';
$query .= " art.id > 0 ORDER BY art._ARTIST_NAME ASC";
if ($uriOffset != '')
$limited = $query . " LIMIT $uriOffset, $perPage";
else
$limited = $query . " LIMIT $perPage";
$noLimit = $this->db->query($query);
$withLimit = $this->db->query($limited);
$numRows = $withLimit->num_rows();
$resultStack = array();
$resultStack = array($numRows);
if($withLimit->num_rows() > 0)
{
$result = $withLimit->result();
$message = '';
}
else
{
$result = NULL;
$message = 'Nema rezultata';
}
array_push($resultStack, $result, $message);
return $resultStack; //$resultStack;
}
所以我真正需要的是,与其运行这两个复杂的查询,我宁愿做一个查询,即使它变得更复杂,但我想从中获得总行数。
我读了一些关于 sql_calc_found_rows 的东西,但无法实现它,因为我完全不熟悉它,而且很多人说它给数据库带来了额外的压力,所以它应该只在极少数情况下使用。
任何帮助将不胜感激!