MySQL防止第一行被删除

时间:2018-08-07 08:10:11

标签: mysql sql

我有一个MySQL表,该表的第一行是默认行,不应删除,但我的同事经常会截断整个表。

我可以将该行标记为重要行还是将其锁定或类似的操作,以使他们无法删除该行?

1 个答案:

答案 0 :(得分:0)

如果使用DELETE语句,则可以简单地define a trigger其中raises an error

CREATE TRIGGER testdata_before_delete BEFORE DELETE ON testdata FOR EACH ROW BEGIN
    IF OLD.id = 1 THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete first row';
    END IF;
END;

结果:

DELETE FROM testdata;
/* SQL Error (1644): Cannot delete first row */
/* Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 0 of 1 query: 0.000 sec. */

DELETE FROM testdata WHERE id = 1;
/* SQL Error (1644): Cannot delete first row */

DELETE FROM testdata WHERE id > 1;
/* Affected rows: 2  Found rows: 0  Warnings: 0  Duration for 1 query: 0.109 sec. */

不幸的是,这不能阻止TRUNCATE语句,但是您可以拒绝特定用户的DROP权限。