【问题标题】:Sort table records in special order按特殊顺序对表记录进行排序
【发布时间】:2012-12-08 23:19:52
【问题描述】:

我有桌子:

+----+--------+----------+
| id | doc_id | next_req | 
+----+--------+----------+
|  1 |    1   |     4    | 
|  2 |    1   |     3    | 
|  3 |    1   |     0    | 
|  4 |    1   |     2    | 
+----+--------+----------+

id - 自动增量主键。

nex_req - 表示记录的顺序。 (next_req = id 记录)

如何构建 SQL 查询以按此顺序获取记录:

+----+--------+----------+
| id | doc_id | next_req | 
+----+--------+----------+
|  1 |    1   |     4    | 
|  4 |    1   |     2    | 
|  2 |    1   |     3    | 
|  3 |    1   |     0    | 
+----+--------+----------+

解释:

record1 with id=1 and next_req=4 means: next must be record4 with id=4 and next_req=2
record4 with id=5 and next_req=2 means: next must be record2 with id=2 and next_req=3 
record2 with id=2 and next_req=3 means: next must be record3 with id=1 and next_req=0 
record3 with id=3 and next_req=0: means that this is a last record 

我需要在表中存储记录的顺序。这对我很重要。

【问题讨论】:

  • 那么它是按什么顺序排列的?随机?
  • 我可以建议你阅读this Article
  • record1 with id=1 and next_req=4 means: next must be record4 with id=4 and next_req=2 record4 with id=5 and next_req=2 means: next must be record2 with id=2 and next_req=3 record2 with id=2 and next_req=3 means: next must be record3 with id=1 and next_req=0 record3 with id=3 and next_req=0: means that this is a last record
  • 您的行本质上是链表的节点。 SQL 根本不支持这种数据结构

标签: mysql sql hibernate


【解决方案1】:

如果可以,请更改表格格式。不要命名下一条记录,而是按顺序标记记录,以便您可以使用自然的 SQL 排序:

+----+--------+------+
| id | doc_id | sort | 
+----+--------+------+
|  1 |    1   |  1   | 
|  4 |    1   |  2   | 
|  2 |    1   |  3   | 
|  3 |    1   |  4   | 
+----+--------+------+

然后您甚至可以在 doc_id 上进行集群索引,如果您需要针对性能问题进行排序。老实说,如果您需要对行进行重新排序,那么与您使用的链接列表相比,它并没有更多的工作。

【讨论】:

    【解决方案2】:

    我建议修改您的表格并添加另一列 OrderNumber,因此最终按此列排序会很容易。

    虽然这种方法可能存在问题:

    1) 您有现有表,需要设置 OrderNumber 列值。我想这部分很容易。您可以简单地设置初始零值并添加一个 CURSOR,例如在您的记录中移动并增加您的订单号值。

    2) 当表格中出现新行时,您必须修改 OrderNumber,但这取决于您的具体情况。如果您只需要将项目添加到列表的末尾,那么您可以将新值设置为 MAX + 1。在另一种情况下,您可以尝试在插入新项目时编写 TRIGGER 并调用与第 1 点类似的步骤。这可能会对性能造成非常严重的影响,因此您必须仔细研究您的架构,并可能修改这种不寻常的结构。

    【讨论】:

      【解决方案3】:

      我能够在 Oracle 中为您提供解决方案,

      select id,doc_id,next_req from table2 
      start with id = 
      (select id from table2 where rowid=(select min(rowid) from table2))
      connect by prior next_req=id
      

      fiddle_demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-08
        • 2018-06-21
        • 2016-11-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-09
        相关资源
        最近更新 更多