0

How can I reorder the fields in the table during an update.

i.e i have this table:

|id|order|
|1 | 0   |
|2 | 0   |
|3 | 1   |
|4 | 2   |
|5 | 3   |
|6 | 0   |
|7 | 4   |

Now what I want to do is that if id = 3 is deleted the whole order field would be updated to:

|id|order|
|1 | 0   |
|2 | 0   |
|4 | 1   |
|5 | 2   |
|6 | 0   |
|7 | 3   |

Is there a simple solution for this? If there is, how would I do it? I was thinking of checking the fields individually.

i.e if 3 is deleted I would fetch first its order number and check if there are no other id's that hold the same order and if there are none I would proceed to check all the order greater than the order number of id 3 and update them individually.

2
  • What would you do if id = 2 gets deleted? What would be the output in your example? Oct 11, 2013 at 21:13
  • @MostyMostacho it wont update the order, since order 0 is used by 2 id's Oct 11, 2013 at 21:15

1 Answer 1

1

If the id is autonumeric or new ids will always take the max(id)+1 value then :

By updating all the rows after the one you just deleted :

update your_table set order = order - 1 where id> @the_id_you_just_deleted
3
  • This won't work. You are assuming it is sorted by id and that is not the case as he could insert a higher id in the middle (between 2 and 3 in the first example) Oct 11, 2013 at 21:15
  • it seems that way with the data sample in the question. But i will precise it in my answer anyway. Thanks.
    – Jonysuise
    Oct 11, 2013 at 21:25
  • then : update your_table set order = order - 1 where id>=@the_id_you_just_deleted
    – Jonysuise
    Oct 12, 2013 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.