【问题标题】:MySQL pagination on complex multi table queriesMySQL对复杂多表查询的分页
【发布时间】:2012-06-29 16:26:44
【问题描述】:

目前我正在运行这样的 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 个)。

【问题讨论】:

  • 检查是否包含了全局$wpdb;
  • 是的,$wpdb 没有问题,查询工作正常,除了我上面提到的那一行。我一定做错了什么,无法找出那是什么.. :(
  • t1.id AS 'post_id',现在您再次将其称为 t1.id 将其设为 post_id 并告诉我 :)
  • 我改了,但还没有运气..

标签: php mysql pagination wordpress


【解决方案1】:

我认为问题在于 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;
    ";

【讨论】:

    【解决方案2】:

    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_ROWSmysql_num_rows()

    $query = "SELECT SQL_CALC_FOUND_ROWS ...
    

    $result_count = mysql_num_rows();
    

    【讨论】:

    • 我知道这是一个愚蠢的问题,但请给我一个示例/语法,说明我如何将它与$wpdb一起使用
    【解决方案3】:

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

    $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-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多