How can I reorder rows in sql database

后端 未结 14 1854
忘了有多久
忘了有多久 2020-11-28 03:24

Is it possible to reorder rows in SQL database? For example; how can I swap the order of 2nd row and 3rd row\'s values?

The order of the row is important to me since

14条回答
  •  不知归路
    2020-11-28 03:39

    It sounds like you need another column like "ListOrder". So your table might look like:

    BookMark ListOrder
    ======== =========
      d        1
      g        2
      b        3
      f        4
      a        5
    

    Then you can "order by" ListOrder.

    Select * from MyTable Order By ListOrder
    

    If the user can only move a bookmark one place at a time, you can use integers as the ListOrder, and swap them. For example, if the user wants to move "f" up one row:

    Update MyTable
        Set ListOrder=ListOrder+1
            Where ListOrder=(Select ListOrder-1 From MyTable where BookMark='f')
    
    Update MyTable
        Set ListOrder=ListOrder-1
            Where BookMark='f'
    

    If the user can move a bookmark up or down many rows at once, then you need to reorder a segment. For example, if the user wants to move "f" to the top of the list, you need to:

    update MyTable
        Set ListOrder=ListOrder+1
            where ListOrder>=1 -- The New position
                and ListOrder <(Select ListOrder from MyTable where BookMark='f')
    
     update MyTable
         Set ListOrder=1 -- The New Position
             Where Bookmark='f'
    

提交回复
热议问题