【问题标题】:Ignore unique key while updating some rows (mariaDB)更新某些行时忽略唯一键(mariaDB)
【发布时间】:2019-01-10 11:45:43
【问题描述】:

我有下表(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_numberdocument_id 的组合是独一无二的。

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

为此,我使用以下查询:

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

但由于唯一键(sort_numberdocument_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

【问题讨论】:

  • 您需要获取 document_id 的 max(sort_number),然后增加该行的 sort_number
  • order by sort_number desc 添加到您的更新声明中。

标签: mysql database laravel mariadb mariasql


【解决方案1】:

更新忽略是答案

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 2017-10-05
        • 2018-10-26
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 2014-12-15
        • 2016-04-25
        • 2020-09-13
        相关资源
        最近更新 更多