使用php根据自定义条件重新排列行

使用php根据自定义条件重新排列行,php,mysql,sql,sql-order-by,Php,Mysql,Sql,Sql Order By,我必须根据自定义首选项重新排列行 桌子的结构是这样的 id(primary) top title 1 2 t1 2 1 t2 3 5 t3 4 3 t4 5 4 t5 id(primary) top title 6 1 t6 2

我必须根据自定义首选项重新排列行

桌子的结构是这样的

id(primary)    top    title
1              2      t1
2              1      t2   
3              5      t3  
4              3      t4 
5              4      t5     
id(primary)    top    title
6              1      t6
2              2      t2
1              3      t1   
4              4      t4  
5              5      t5 
结果按顶部ASC的顺序显示,其结果如下所示

id(primary)    top    title
2              1      t2
1              2      t1   
4              3      t4  
5              4      t5 
3              5      t3
现在我想把这一行放在顶部,并从结果中删除一行

id(primary)    top    title
6              NULL   t6
并更改/向下推一个位置/重新指定列(顶部)以如下方式显示结果

id(primary)    top    title
1              2      t1
2              1      t2   
3              5      t3  
4              3      t4 
5              4      t5     
id(primary)    top    title
6              1      t6
2              2      t2
1              3      t1   
4              4      t4  
5              5      t5 
也就是说,所有以前的顶级排序行现在被下推一个位置,并且删除了带有top=5的行
id=3
,就像带有top=NULL的
id=3

实现这一点的简单方法是将列(顶部)重新分配到所需的首选项,但我不能这样做,因为有数百行要处理,所以我需要一些自动逻辑


请查看并建议任何可能的方法。

大致如下:

array_pop( $results ); // Remove last row
array_unshift( $results, $new_row ); // Add new row to the beginning
foreach( $results as $index => &$value )
    $value['top'] = $index+1; //Reassign top so that it matches the index of the numerical array, which will always start counting from zero
select id, ifnull(top, 0)+1, title from theTable order by 2
或者如果上面有多个

SELECT * FROM theTable ORDER BY id in (id,id,id) DESC, top ASC

这只是一排吗?或者,您希望对所有具有空顶部值的行执行此操作?这是针对我希望显示在所需位置的任何一行。因此,基本上,当您执行查询时,您希望具有特定id的行显示在顶部,然后其他行将正确排序?如果我希望在第二位而不是顶部显示行,该怎么办,我想从显示的结果中删除行,而不是从表中删除行。这与显示结果所用的代码有关。例如,如果使用For循环显示结果,只需从索引1开始,而不是从0开始。如果我希望该行位于任何位置,如何更改插入行下方行的顶部值。@TallboY哦,对不起,我可以;我帮不了你。但是你仍然可以在php上完成。你的第二个例子可能可以,但问题是我有30个结果要显示,所以我必须按照所需的顺序编写所有30个ID,有没有办法自动/预先制作/重新安排顺序。+1 mate!我想投票给所有发表好答案的人,也给其他人空间和分享:D你是他们中的一员!
select
  id,
  case when id=6 then 1 else top+1 end top,
  title
from
  your_table
where
  id=6 or
  top!=(select max(top) from your_table where id!=6)
order by top