MySql 使用唯一键约束增加单元格值
MySql Incrementing a cell value with a Unique Key constraint
我有一个 table 可以排序的项目,看起来有点像这样:
CREATE TABLE `mytable` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(1024) NOT NULL,
`position` int(11) NOT NULL
PRIMARY KEY (`uid`),
UNIQUE KEY `Position_UNIQUE` (`position`)
)
如您所见,位置必须是唯一的。现在,每当我向 table 中插入一条新记录时,我希望它的位置为 #1,因此我需要将所有其他值递增一个。
如果我去
update mytable set position = position + 1
我可以投诉我的唯一键限制被违反(错误代码:1062。键 'Position_UNIQUE' 的重复条目“2”)。
我该如何巧妙地做到这一点?
您需要添加一个 "order by" 子句:
update mytable set position = position + 1 order by position desc;
我有一个 table 可以排序的项目,看起来有点像这样:
CREATE TABLE `mytable` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(1024) NOT NULL,
`position` int(11) NOT NULL
PRIMARY KEY (`uid`),
UNIQUE KEY `Position_UNIQUE` (`position`)
)
如您所见,位置必须是唯一的。现在,每当我向 table 中插入一条新记录时,我希望它的位置为 #1,因此我需要将所有其他值递增一个。
如果我去
update mytable set position = position + 1
我可以投诉我的唯一键限制被违反(错误代码:1062。键 'Position_UNIQUE' 的重复条目“2”)。
我该如何巧妙地做到这一点?
您需要添加一个 "order by" 子句:
update mytable set position = position + 1 order by position desc;