2012-06-29 64 views
0

目前我正在一个MySQL查询像这样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给我想要的值。

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

+0

检查是否包含全局$ wpdb; – swapnesh

+0

是的,没有'$ wpdb'的问题,查询工作正常,除了我上面提到的那一行。我必须做错了什么,不能找出那是什么.. :( – Anuj

+0

t1.id AS'post_id',现在你又指t1.id让它post_id并让我知道:) – swapnesh

回答

0

我试过很多,但没” t成功了,所以我又做了另一个单独的数据库查询以进行分页。

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

它给我,我可以使用分页行数总的结果。

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; 
    "; 
0

COUNT(DISTINCT X) .. GROUP BY X一个quesy总是会导致值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(); 
+0

我知道这是一种愚蠢的问题,但你可以请给我一个例子/语法如何我可以使用它'$ wpdb' – Anuj