2012-08-14 31 views
0

我有一個查詢連接3個表並返回按頁碼排序的結果,因此我一次只能查看一個頁面,並能通過數組查看其輸出。從子查詢結果中獲取MAX(value)

這裏是我的查詢

select wo.*, 
    (select count(distinct order) 
    from (SELECT * 
      FROM `movements` LEFT JOIN 
       `classes` 
       ON `movements`.`class_id` = `classes`.`class_id` LEFT JOIN 
       `clients` 
       ON `movements`.`class_id` = `clients`.`class_id` 
      WHERE `classes`.`class_id` = '$class_id' 
     ) wo2 
    where wo2.order <= wo.order 
    ) as pagenum 
from (SELECT * 
    FROM `movements` LEFT JOIN 
     `classes` 
     ON `movements`.`class_id` = `classes`.`class_id` LEFT JOIN 
     `clients` 
     ON `movements`.`class_id` = `clients`.`class_id` 
    WHERE `classes`.`class_id` = '$class_id' 
) wo 
order by pagenum 

現在我希望能夠得到MAX(頁次),所以我可以告訴PHP時,我已經達到了查詢結束。有沒有辦法做這樣的事情(我曾經試過,但不斷收到SQL語法錯誤)

SELECT MAX(`pagenum`) as `lastpage` 

還是有更好的方式來做到這一點?

下面是該查詢結果的屏幕截圖。我目前有一個「下一個」和「上一個」鏈接,當頁面到達查詢結束時(這些結果中的第5頁),我們希望讓PHP不再提供轉到下一頁的選項。所以我不知何故必須得到每個查詢的MAX(pagenum)的值。

http://custommovement.com/help/woquery.png

回答

1

您可以通過另一相關子查詢得到maxpage民:

select wo.*, 
     (select count(distinct order) 
     from (SELECT * 
       FROM `movements` LEFT JOIN 
        `classes` 
        ON `movements`.`class_id` = `classes`.`class_id` LEFT JOIN 
        `clients` 
        ON `movements`.`class_id` = `clients`.`class_id` 
        WHERE `classes`.`class_id` = '$class_id' 
      ) wo2 
     where wo2.order <= wo.order 
     ) as pagenum, 
     (select count(distinct order) 
     from (SELECT * 
       FROM `movements` LEFT JOIN 
        `classes` 
        ON `movements`.`class_id` = `classes`.`class_id` LEFT JOIN 
        `clients` 
        ON `movements`.`class_id` = `clients`.`class_id` 
        WHERE `classes`.`class_id` = '$class_id' 
      ) wo2 
     ) as maxpages   
from (SELECT * 
     FROM `movements` LEFT JOIN 
      `classes` 
      ON `movements`.`class_id` = `classes`.`class_id` LEFT JOIN 
      `clients` 
      ON `movements`.`class_id` = `clients`.`class_id` 
     WHERE `classes`.`class_id` = '$class_id' 
    ) wo 
order by pagenum 
+0

真棒!!!!作品!!!謝謝@GordonLinoff。 – Colbyd 2012-08-14 20:41:11