2012-06-29 52 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