从子查询结果中获取MAX(值)

时间:2012-08-14 19:42:03

标签: php mysql

我有一个连接3个表的查询并返回按页码排序的结果,因此我一次只能查看一个页面,并通过数组输出它。

这是我的查询

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(pagenum),这样当我到达查询结束时我就能告诉PHP。有没有办法做这样的事情(我已经尝试但继续得到sql语法错误)

SELECT MAX(`pagenum`) as `lastpage`

或者有更好的方法来实现这个目标吗?

以下是此查询结果的屏幕截图。我目前有“下一个”和“上一个”链接,当我到达查询结束时,用户从页面到页面(这些结果中的第5页)我想让PHP不再提供转到下一页的选项。所以我不得不得到每个查询的MAX(pagenum)的值。

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

1 个答案:

答案 0 :(得分:1)

您可以通过包含另一个相关子查询来获取最大页码:

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