1

MYSQL 查询以获取相邻行以及当前(id)给定条件

喜欢

ID | BOOK     |
--------------
1  | xyzbooks |

2  | pqrbooks |

3  | dnsaddds |

4  | dfbsakjf |

5  | dbsadbdd |

6  | tyrbooks |

7  | sfdffdsf |

8  | yuibooks |

我在 id 3 上(我可以从 url 获得的 dnsaddds)并且我搜索了书籍。现在我需要获取第三行的行数据,以及搜索文本(书籍)的下一个和上一个结果

预期结果如下

ID | BOOK     | AUTHOR | DATE
---------------------------
2  | pqrbooks | fbsdjf | 2013

3  | dnsaddds | fdsfbs | 2012

6  | tyrbooks | fdsdff | 2011

寻找没有联合等的单个查询。

4

2 回答 2

2

这应该有效:

select id, book, author, date
from t
where id = 3
      OR id = (SELECT MAX(id) FROM t WHERE id < 3)
      OR id = (SELECT MIN(id) FROM t WHERE id > 3)
于 2013-04-24T13:12:34.537 回答
0

您可以union通过将所需的三行组合在一起来做到这一点:

(select id, book, author, date
 from t
 where id = 3
) union all
(select id, book, author, date
 from t
 where id < 3 and book like '%books%'
 order by id desc
 limit 1
) union all
(select id, book, author, date
 from t
 where id > 3 and book like '%books%'
 order by id
 limit 1
)
于 2013-04-23T18:55:57.583 回答