0

目前我正在运行这样的 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;
}

link_count然后该值与下一行中声明的值相同,COUNT( t2.link_id ) AS 'link_count',给出了我想要的值。

请给我一些关于如何在此查询上使用分页(如 30 个结果中的 10 个)的想法。

4

3 回答 3

0

我尝试了很多但没有成功,所以我为分页做了另一个单独的数据库查询。

$page_query = "
    SELECT p.id 
    FROM 
    $posts_table as p, 
    $tag_table as c
    WHERE p.id=c.post_id
    GROUP BY p.id
";

它给了我可以用于分页的总行数的结果。

于 2012-06-29T08:26:44.397 回答
0

我认为问题出在 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;
    ";
于 2012-06-29T07:24:43.847 回答
0

一个 quesy likeCOUNT( DISTINCT X ) .. GROUP BY X总是会产生值 1,如果你跳过 DISTINCT,你会得到组合连接的数量

有一些方法可以在 mysql 中获取计数,但它更容易使用mysql_num_rows()count()在 php 中。

$results = $wpdb->get_results($query);

foreach($results as $result)
{
    $result->row_count =  count($results);
    ...
}

上面只显示获取的行数,如果你想要你需要使用的总数SQL_CALC_FOUND_ROWSmysql_num_rows()

$query = "SELECT SQL_CALC_FOUND_ROWS ...

$result_count = mysql_num_rows();
于 2012-06-29T07:25:29.060 回答