本文介绍了如何防止创建两个字段的值相同的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表.
CREATE TABLE people(
first_name VARCHAR(128) NOT NULL,
nick_name VARCHAR(128) NULL
)
我想防止人们在尝试插入时将其昵称与姓氏相同.我不想在任何一列上创建索引,只是为了防止在first_name和nick_name相同的情况下插入记录.
I would like to prevent people from having their nickname be the same as their firstname if they attempt that insertion. I do not want to create an index on either of the columns just a rule to prevent the insertion of records where the first_name and nick_name are the same.
有没有一种方法可以创建规则来防止在first_name
等于nick_name
的位置插入记录?
Is there a way to create a rule to prevent insertion of records where the first_name
would equal the nick_name
?
推荐答案
CREATE TRIGGER `nicknameCheck` BEFORE INSERT ON `people` FOR EACH ROW begin
IF (new.first_name = new.nick_name) THEN
SET new.nick_name = null;
END IF;
END
或者您可以将first_name设置为NULL,这将导致SQL错误,并且您可以处理它并显示一些警告.
Or you can set first_name to NULL which will cause SQL error and you can handle it and show some warning.
这篇关于如何防止创建两个字段的值相同的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!