dptj13337 2012-08-22 22:06
浏览 34
已采纳

在按字母顺序排列搜索词之前和之后选择n行

Dilemma: I have a table with several hundred rows in it. I would like to submit a mysql_query with a specific search term wherein the query finds where the term would be located alphabetically in the column and then returns the n rows before the placement and n rows after the placement.

Example: Imagine that I have a column like the following (I'm placing it horizontally for the sake of space, but for sake of argument, let's pretend that this is a vertical list of column values):

|apple|asus|adder|billy|cat|dog|zebra|computer|mouse|cookie|donkey|

If I were to run the query on the term courage, assuming n = 3, I would like to have it return the following rows in this order:

|cat|computer|cookie|dog|donkey|mouse|

Alphabetically, the word courage would land right in the middle of those results and we are met with the preceding 3 entries and the following 3 entries.

Language Notes: I'm using php and mysql. I don't have any code to display because I'm not sure whether this needs to be in the where clause, or if it requires a subquery, or if you need to do something with the variable in php before handing it to the query.

  • 写回答

1条回答 默认 最新

  • dousi6087 2012-08-22 22:11
    关注

    You might try an UNION of two SELECTS. Or do it manually.

    SELECT term FROM table WHERE term < 'courage' ORDER BY term DESC LIMIT 3;
    

    will return cookie, computer and cat (in descending order).

    Then SELECT term FROM table WHERE term >= 'courage' ORDER BY term ASC LIMIT 3;

    will return dog, donkey and mouse.

    In PHP, you get the two sets, reverse the first and join.

    A wholly-SQL solution might be

    SELECT term FROM (
        SELECT term FROM table WHERE term < 'courage' ORDER BY term DESC LIMIT 3 )
        UNION
        SELECT term FROM table WHERE term >= 'courage' ORDER BY term ASC LIMIT 3 )
    ) ORDER BY term;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错