我目前正在使用数据库表,其结构如下:
______________________________
| id | content | next_id |
|------|-----------|-----------|
| 1 | (value) | 4 |
| 2 | (value) | 1 |
| 3 | (value) | (NULL) |
| 4 | (value) | 3 |
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
next_id
字段的值定义了应该跟随它的数据行的id。值NULL
表示后面没有行。
有没有办法可以查询数据库,以便在结果行中使用此方法进行排序?例如,在我上面给出的情况下,行应该按顺序返回,以便id按以下顺序排列:2
,1
,4
,3
。我正在寻找一种解决方案,无论此序列中的行数如何,都可以执行此操作。
我知道可以在从数据库中检索结果后重新排序结果(使用我正在使用的编程语言),但是我希望有一种方法可以在SQL中实现。< / p>
答案 0 :(得分:0)
如果没有像行一样多的自连接,我看不到解决方案。相反,我会使用下推堆栈算法在临时表中构建一个嵌套的集合,然后检索一个完整的树。
答案 1 :(得分:0)
我有一些接近的东西。
/*one select to init the @next variable to the first row*/
select @next:= id from table1 order by isnull(next_id) asc, next_id asc limit 1;
select distinct a.id, a.next_id from table1 b
inner join
(
select @rank:= id as id, @next:= next_id as next_id from table1
where id = @next
) a
on (b.id = b.id);
此输出
+----+---------+
| id | next_id |
+----+---------+
| 2 | 1 |
| 1 | 4 |
然后停下来。如果我能找到继续它的方法......
无论如何,在进行排名时,将这些值输入查询的这种力量是狡猾的,更不用说这种东西,所以也许我会走向死胡同。