1

我有下表(mariaDB):

+----+--------------+-------------+-------------+
| id | content_type | sort_number | document_id |
+----+--------------+-------------+-------------+
|  1 | text         |           1 |           1 |
|  2 | table        |           2 |           1 |
|  3 | text         |           3 |           1 |
|  4 | image        |           4 |           1 |
+----+--------------+-------------+-------------+

sort_number和的组合document_id是独一无二的。

现在,当我想在位置 2 处添加一个新条目时,我需要将sort_number所有条目中的sort_number >= 2增加一个步骤。

为此,我使用以下查询:

update `table_name` set `sort_number` = sort_number +1 where `sort_number` > ? and `document_id` = ?

但是由于唯一键 ( sort_numberand document_id) 我得到一个错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'table_name_sort_number_document_id_unique'

我厌倦了避免错误SET unique_checks=0;但仍然得到错误......

有没有(更好的)方法来更新sort_number一个查询?

4

3 回答 3

1

ORDER BY 也适用于更新查询,所以很简单:

SET @i:=0;
UPDATE items SET disp_order=@i:=@i+1 ORDER BY item_name;

只需从最后一行开始更新并向后遍历。

于 2018-08-02T16:27:26.980 回答
0

我喜欢 Paul Spiegel 提供的解决方案。我的查询现在看起来像这样:

update `table_name` set `sort_number` = sort_number +1 where `sort_number` > ? and `document_id` = ? order by `sort_number` desc
于 2018-08-03T07:15:23.017 回答
0

更新忽略是答案

UPDATE IGNORE `table_name` set `sort_number` = sort_number +1 where `sort_number` > ? and `document_id` = ?
于 2021-11-21T14:25:20.153 回答