【发布时间】: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=2record4 with id=5 and next_req=2 means: next must be record2 with id=2 and next_req=3record2 with id=2 and next_req=3 means: next must be record3 with id=1 and next_req=0record3 with id=3 and next_req=0: means that this is a last record -
您的行本质上是链表的节点。 SQL 根本不支持这种数据结构