gpt4 book ai didi

MySQL 触发器 - 触发器表名称解释为字段

转载 作者:行者123 更新时间:2023-11-29 09:53:09 25 4
gpt4 key购买 nike

我在正在构建的数据库中放入的触发器有问题。它是数据库中唯一的触发器。这是正在使用的两个表。

客户表

create table client (
clientNum INT(5) not null auto_increment,
clientName TEXT(30) not null,
clientEmail VARCHAR(64) not null,
clientGender CHAR(1) not null,
clientDOB DATE not null,
clientAddress TEXT(50),
clientPhone VARCHAR(12) not null,
hasInsurance CHAR(1) not null,
clientBalanceOwed DECIMAL(10,2),
clientLastDateVisited DATE,
clientNextVisitDate DATE,
primary key (clientNum));

保险表

create table insurance(
insuranceNum INT(5) not null auto_increment,
cardNum INT(16),
policyNum INT(6),
policyHolder TEXT(30),
clientNum INT(5),
primary key (insuranceNum),
foreign key (clientNum) references client(clientNum));

以下触发器的想法是仅当将客户端添加到“hasInsurance”字段设置为“y”的数据库时才创建保险行。然后,添加该客户端后,创建一个新的保险行,并将 clientNum 设置为刚刚添加的 clientNum。

触发器

delimiter $$
create trigger New_Insurance_Row after insert on client
for each row
begin
if(client.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
end$$

到目前为止,一切都按预期进行,直到您尝试将新客户端插入表中并调用触发器。一旦我尝试添加以下代码行:

插入语句

insert into client(clientName, clientEmail, clientGender, clientDOB, 
clientAddress,
clientPhone, hasInsurance, clientBalanceOwed, clientLastDateVisited,
clientNextVisitDate)
values
('Darcy Watts','dwatts@email.com','m','1996-5-9','Belfast, Charlottetown
PEI','123-222-3333','y','400.77','2017-8-12','2019-9-6');

当我尝试运行此程序时,我遇到了以下错误:

#1109 - Unknown table 'client' in field list

所以从我过去几个小时了解到的情况来看,当你将“`”(反引号)放在变量或表名上时,通常会发生此错误,MySQL 认为该条目是字段列表或其他内容的一部分沿着那条线。所以我将触发器本身更改为“客户端”,但仍然出现错误。删除旧数据库和所有内容。另一件事是,如果尚未输入触发器,则插入语句会自行工作。

如有任何帮助,我们将不胜感激!谢谢!

最佳答案

我猜您的 hasInsurance 应该来自new 记录。

...
if(new.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
...

--

DB Fiddle (由GMB提供)

关于MySQL 触发器 - 触发器表名称解释为字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54431789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com