简体   繁体   English

订购并更改数据库的一列

[英]order and change one column of database

I have one col in my database named position used for ordering. 我的数据库中有一个col命名为position用于订购。 However, when some records is deleted, the sequence get messed up. 但是,当删除某些记录时,该序列会变得混乱。 I want to reorder this col when the table is changed(maybe use trigger). 我想在更改表时重新排序此col(也许使用触发器)。

position(old)    ->  position(new)
       1                    1
       3                    2
       7                    3
       8                    4

like this. 像这样。 I think there will not exist equal number even in position(old), because I have already attach some function in PHP to reorder the column when updates occurs. 我认为即使在position(old)中也不会存在相等的数字,因为我已经在PHP中附加了一些函数,以便在更新发生时对列进行重新排序。 However, when a record is deleted because of the deletion of its parent , function will not be called. 但是,由于记录的parent而删除记录时,将不会调用该函数。
Thanks for help! 感谢帮助!

If you are using the column just for ordering, you do not need to update column on deletion, because the order will still be correct. 如果您仅使用该列进行订购,则删除时无需更新该列,因为顺序仍然正确。 And you will save some resources. 这样您将节省一些资源。

But if you really need to update by sequence, look at this answer: 但是,如果您确实需要按顺序进行更新,请查看以下答案:

updating columns with a sequence number mysql 用序列号mysql更新列

I believe (as scrowler wrote) the better way in such case is to update rows from the application, after application deletes the parent record. 我相信(如scrowler所写),在这种情况下,更好的方法是在应用程序删除父记录之后从应用程序更新行。

If you decide to update it in the application then... 如果您决定在应用程序中对其进行更新,则...

If position = n is deleted, you logic should be set position = position - 1 where position > n 如果删除了position = n,则应将您的逻辑设置为position = position-1,其中position> n

Please note that this will work only if you delete one record at a time from your application and before assuming that before the delete is triggered the data is already in sequence 请注意,仅当您一次从应用程序中删除一条记录并且在假定触发删除操作之前数据已经按顺序删除之前,这才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM