changing existing duplicate entries in mysql

孤者浪人 提交于 2019-12-11 05:26:50

问题


sorry for the (probably) noob question, but I', new at this stuff.

i have a table that has column 'position', and I want to, when inserting a new row, change positions of every row that has position lower than row that is inserted. for example, if I add row with position 4, if there is a duplicate, it should become 5, 5 should shift to 6 and so on...

also, is there a way to get highest value for column besides testing it in every row via php?


回答1:


You need two queries. Assuming you know the position you're inserting, increase the position of each row that has position greater than or equal to the position you're inserting:

UPDATE table SET position = position + 1 WHERE position >= newPosition

After that, the newPosition can be inserted and no duplicates will exist:

INSERT INTO table SET position = newPosition

To get the highest value, you can use MAX()

SELECT MAX(position) FROM table


来源:https://stackoverflow.com/questions/2807071/changing-existing-duplicate-entries-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!