[英]MySQL pagination on complex multi table queries
目前,我正在运行这样的MySQL查询
$query = "
SELECT
t1.id AS 'post_id',
t1.post_title AS 'post_title',
t1.post_status AS 'post_status',
COUNT( t1.id ) AS 'row_count', //this one is not working
COUNT( t2.tag_id ) AS 'link_count',
GROUP_CONCAT( t2.tag_id) AS 'link_id',
GROUP_CONCAT( t2.url) AS 'url',
GROUP_CONCAT( t2.title) AS 'title',
GROUP_CONCAT( t2.active) AS 'active',
FROM $posts_table AS t1
JOIN $tags_table AS t2 ON ( t1.id = t2.post_id )
GROUP BY t1.id
ORDER BY t1.id DESC
LIMIT $start_from, $row_to_show;
";
除了COUNT( t1.id ) AS 'row_count',
行之外,此查询的每个部分都执行良好。
我想计算在t1表中找到的行总数,但是当我转储数组时
$result = $wpdb->get_results($query);
var_dump($result->row_count);
它给了我NULL
。
如果我在循环中使用它
foreach ( $result as $result ){
echo $result->row_count;
}
然后,该值与在下一行COUNT( t2.link_id ) AS 'link_count',
声明的link_count
相同COUNT( t2.link_id ) AS 'link_count',
给出我想要的值。
请给我一些关于如何在此查询上使用分页(例如30个结果中的10个)的想法。
我认为问题出在GROUP BY。
试试这个查询:
$query = "
SELECT
t1.id AS 'post_id',
t1.post_title AS 'post_title',
t1.post_status AS 'post_status',
COUNT( t1.id ) AS 'row_count',
COUNT( t2.tag_id ) AS 'link_count',
GROUP_CONCAT( t2.tag_id) AS 'link_id',
GROUP_CONCAT( t2.url) AS 'url',
GROUP_CONCAT( t2.title) AS 'title',
GROUP_CONCAT( t2.active) AS 'active',
FROM $posts_table AS t1, $tags_table AS t2
GROUP BY t1.id
HAVING t1.id = t2.post_id
ORDER BY t1.id DESC
LIMIT $start_from, $row_to_show;
";
像COUNT( DISTINCT X ) .. GROUP BY X
类的问题。GROUP COUNT( DISTINCT X ) .. GROUP BY X
将始终得出值1,如果跳过DISTINCT,您将获得组合联接的数量
有多种方法可以在mysql中获取计数,但仅在php中使用mysql_num_rows()
或count()
轻松实现。
$results = $wpdb->get_results($query);
foreach($results as $result)
{
$result->row_count = count($results);
...
}
上面仅显示获取的行数,如果需要总计,则需要使用SQL_CALC_FOUND_ROWS
和mysql_num_rows()
$query = "SELECT SQL_CALC_FOUND_ROWS ...
和
$result_count = mysql_num_rows();
我尝试了很多,但没有成功,因此我仅针对分页进行了另一个单独的数据库查询。
$page_query = "
SELECT p.id
FROM
$posts_table as p,
$tag_table as c
WHERE p.id=c.post_id
GROUP BY p.id
";
它给了我可用于分页的总行数的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.