获得下一个最低ID或最高ID?

时间:2017-11-17 13:02:17

标签: mysql

这是我到目前为止的SQL:

  SELECT  `cimg`.*,
          `pimg`.`id` as `prev`,
          `nimg`.`id` as `next`
  FROM    `images` as `cimg`,
          `images` as `pimg`,
          `images` as `nimg`
  WHERE   `cimg`.`id` = :id AND
          `pimg`.`id` = (
            SELECT  max(`id`)
            FROM    `images`
            WHERE   `id` < :id
          ) AND
          `nimg`.`id` = (
            SELECT  min(`id`)
            FROM    `images`
            WHERE   `id` > :id
          )

它基本上从一行中选择所有数据,然后选择它上面和下面的行的id

但是当当前行是其中一个极端时,我需要它来获取其id(如果它是最低的)或prev的另一个极端的next (如果它是最伟大的)。

有点像旋转木马或循环。例如。我们有一张表id的2,5,10,20和53。

如果它是当前行的最低行,我们将返回id 2行的所有数据以及另外两列; 53prev5next

1 个答案:

答案 0 :(得分:1)

基本上你想要做的就是检查是否有值。如果子查询中没有值,则应返回MAX()MIN() id的值。

不确定这是否是最佳选择,但它应该可以解决问题。

SELECT 
    `cimg`.*, `pimg`.`id` AS `prev`, `nimg`.`id` AS `next`
FROM
    `images` AS `cimg`,
    `images` AS `pimg`,
    `images` AS `nimg`
WHERE
    `cimg`.`id` = :id
AND `pimg`.`id` = 
    CASE WHEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id) IS NOT NULL 
        THEN (SELECT MAX(`id`) FROM `images` WHERE `id` < :id)
        ELSE (SELECT MAX(`id`) FROM `images`)
    END 
AND `nimg`.`id` = 
    CASE  WHEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id) IS NOT NULL
        THEN (SELECT  MIN(`id`) FROM `images` WHERE `id` > :id)
        ELSE (SELECT  MIN(`id`) FROM `images`)
    END
;