【问题标题】:how to get alphabetically next and prev records wiht minimal fetched records?如何以最少的获取记录按字母顺序获取下一个和上一个记录?
【发布时间】:2010-03-05 11:47:17
【问题描述】:

我有一个页面,其中显示了表 A 中的公司名称及其详细信息。 现在假设我显示了一家公司,它的名称是“Company_one”,现在我想按字母顺序对下一家公司和上一家公司及其详细信息等进行排序。

我的表中的数据没有排序。它在获取数据时存储。

那么现在我应该写什么样的查询,它只给出一个前一个和一个下一个按字母排序的记录? 请帮忙!!

【问题讨论】:

  • 你的表有索引吗?

标签: sorting mysql alphabetical


【解决方案1】:

在单个查询中没有很好的方法可以做到这一点。只需执行两个查询。

获取上一个:

SELECT * FROM companies
WHERE name < variable_with_current_name
ORDER BY name DESC
LIMIT 1

继续下一个:

SELECT * FROM companies
WHERE name > variable_with_current_name
ORDER BY name ASC
LIMIT 1

【讨论】:

    【解决方案2】:

    您需要使用 sort clause 对表格进行排序。 sort 的原型是:

    sort by fieldname
    

    示例查询:

    select * from your_table sort by company asc
    

    如果要限制记录,使用limit子句:

    select * from your_table sort by company asc limit 0, 1
    

    【讨论】:

      【解决方案3】:

      根据 Dominic 的回答,您可以通过将它们与 WHEREOR 组合使用单个查询来获得相同的结果。

      例如:

      SELECT * FROM `companies`
      WHERE (
          `name` = IFNULL(
              (SELECT `name` FROM `companies` 
                  WHERE `name` < 'variable_with_current_name'
                  ORDER BY `name` DESC
                  LIMIT 1)
              , 0)
      OR
          `name` = IFNULL(
              (SELECT `name` FROM `companies` 
                  WHERE `name` > 'variable_with_current_name'
                  ORDER BY `name` ASC
                  LIMIT 1)
              , 0)
      ) 
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2022-12-04
        • 1970-01-01
        • 2021-04-06
        • 2021-11-25
        • 1970-01-01
        • 2015-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多