MySQL 检查 table 是否只包含这个特定类型
MySQL check if the table only contains this certain type
delimiter $$
CREATE Trigger TreeTest
after insert on trees
for each row
begin
if (select type from trees) != 'oak' OR (select type from trees ) != 'burch' OR (select type from trees ) != 'maple' OR (select type from trees ) != 'tulpin' then
set message_text = 'You do not have the right tree';
end if;
end; $$
delimiter ;
我在 MySQL 中使用了此代码,但它总是使用来自 table 的数据向触发器发出警报,而它不应该我哪里出错了?
目标是检查 table 中是否只有这三种类型。如果不报错。
您有几个选择:
将 type
列数据类型更改为 ENUM('oak', 'burch', 'maple', 'tulpin')
用这些类型创建另一个 table,将这些树放在那里并在 table
[=23 中使用 type_id(FK) =]
Create BEFORE INSERT/UPDATE 触发并检查是否不允许 NEW.type 以防止将类型为 table 的记录添加到 table.
The goal is to check if only these three types are in the table. If not give an error.
你似乎把这个复杂化了。如果你想确保给 type
列的任何值都属于预定义列表,你可以只使用 ENUM
column,像这样:
ALTER TABLE `trees` CHANGE `type` `type` ENUM('oak', 'burch', 'maple', 'tulpin');
使用此设置,您可以放心,除了列表中声明的值之外,列中将不允许使用其他值(任何尝试提供未声明的值都会引发错误)。
delimiter $$
CREATE Trigger TreeTest
after insert on trees
for each row
begin
if (select type from trees) != 'oak' OR (select type from trees ) != 'burch' OR (select type from trees ) != 'maple' OR (select type from trees ) != 'tulpin' then
set message_text = 'You do not have the right tree';
end if;
end; $$
delimiter ;
我在 MySQL 中使用了此代码,但它总是使用来自 table 的数据向触发器发出警报,而它不应该我哪里出错了?
目标是检查 table 中是否只有这三种类型。如果不报错。
您有几个选择:
将
type
列数据类型更改为 ENUM('oak', 'burch', 'maple', 'tulpin')用这些类型创建另一个 table,将这些树放在那里并在 table
[=23 中使用 type_id(FK) =]Create BEFORE INSERT/UPDATE 触发并检查是否不允许 NEW.type 以防止将类型为 table 的记录添加到 table.
The goal is to check if only these three types are in the table. If not give an error.
你似乎把这个复杂化了。如果你想确保给 type
列的任何值都属于预定义列表,你可以只使用 ENUM
column,像这样:
ALTER TABLE `trees` CHANGE `type` `type` ENUM('oak', 'burch', 'maple', 'tulpin');
使用此设置,您可以放心,除了列表中声明的值之外,列中将不允许使用其他值(任何尝试提供未声明的值都会引发错误)。