在ONE ROW中获取预览下一条记录

时间:2017-09-16 21:26:29

标签: mysql select

我希望在一行中获得上一个\下一个ID。如果不是next或prev rec的值,则它必须为NULL。

mysql> select picsid  from pics where  albid_pics=15;
+--------+
| picsid |
+--------+
|    110 |
|    111 |
|    112 |
|    113 |
|    114 |
|    115 |
|    116 |
|    117 |
|    131 |
|    132 |
|    133 |
|    134 |
|    135 |
|    136 |
|    153 |
|    154 |
|    155 |
|    156 |
|    157 |
|    159 |
|    160 |
+--------+
21 rows in set (0.00 sec)

mysql> 

1。如果我做

(select picsid prv from pics where picsid<136 and albid_pics=15 order by prv desc limit 1)
union
(select picsid nxt from pics where picsid>136 and albid_pics=15 order by nxt asc limit 1);
+-----+
| prv |
+-----+
| 135 |
| 153 |
+-----+
2 rows in set (0.00 sec)

mysql> 

但我想在一排获得qresult,

2

mysql> (select picsid prv from pics where picsid<160 and albid_pics=15 order by prv desc limit 1)  union  (select picsid nxt from pics where picsid>160 and albid_pics=15 order by nxt asc limit 1);
+-----+
| prv |
+-----+
| 159 |
+-----+
1 row in set (0.00 sec)

mysql> 

如果不是next或prev记录的值,则它必须为NULL。

这是什么?

1 个答案:

答案 0 :(得分:2)

您正在寻找的内容非常简单。例如,这个:

SELECT (1+1) AS sum1,(2+2) AS sum2

将导致:

+------+------+
| sum1 | sum2 |
+------+------+
|    2 |    4 |
+------+------+

您所要做的就是将子查询放在那里:

SELECT (SELECT picsid 
        FROM pics 
        WHERE picsid < 136 AND 
              albid_pics = 15 
        ORDER BY picsid DESC 
        LIMIT 1) AS previous,
        (SELECT picsid 
        FROM pics 
        WHERE picsid > 136 AND 
              albid_pics = 15 
        ORDER BY picsid ASC 
        LIMIT 1) AS `next`;

注意:next是MySQL中的关键字,因此是反引号。