如何使用Trigger更新表中与另一个表中的数据相关的字段

时间:2014-03-10 14:20:41

标签: mysql triggers

我有两个表,即 Enquiry_details Customer_details ,如果 Enquiry_details 表中的客户名称已在customer_details表中,则需要更新Enquiry_details现有客户字段的表状态为YES,否则为No.

这应该使用触发器来完成。请帮助解决触发器代码。

谢谢, Acube。

2 个答案:

答案 0 :(得分:0)

create trigger track_customer before insert on enquiry_details for each row begin if (select count(*) from customer_details where customer_name = NEW.customer_name) <= 0 then set NEW.existing_customer = 'No'; else set NEW.existing_customer = 'Yes'; end if; end;//

答案 1 :(得分:0)

工作代码如下。感谢 Clement89 帮助我。

create trigger track_customer_Exists 
before insert on enquiry_details 
for each row
BEGIN
  INSERT INTO enquiry_details_seq VALUES (NULL);
  SET NEW.Created_Date = NOW();
  SET NEW.Submitted_Date = NOW();
  SET NEW.Slno = coalesce((select max(Slno) from enquiry_details), 0) + 1;
  SET NEW.Enq_Id = CONCAT('ENQ', LPAD(LAST_INSERT_ID(), 5, '0'));
if (select count(*) from customer_details where Customer_Name = NEW.Customer_Name) <= 0 
then 
set NEW.Existing_Customer = 'No'; 
else 
set NEW.Existing_Customer = 'Yes'; 
end if;
END