删除MYSQL中的触发器

时间:2012-12-06 17:05:10

标签: mysql

我已将此代码发布在另一个威胁中,但这个问题略有不同。我必须触发。问题听起来像这样:

  

“创建一个触发器,在每次使用时删除该季节   关于何时和谁生产产品的信息被删除(即,   每当从'Produces'表中删除记录时,检查是否存在   关于同一季节生产的产品的其他记录,如果   不,也从季节表中删除相应的记录)“

我的MYSQL代码:

MYSQL代码在这里:

CREATE TABLE IF NOT EXISTS Dvds(
Serial integer NOT NULL,
Name varchar(50),
Year integer,
Genre varchar(50),
Price integer,
PRIMARY KEY (Serial));

CREATE TABLE IF NOT EXISTS Shops(
Id integer NOT NULL,
Name varchar(50),
Address varchar(50),
PRIMARY KEY (Id));

CREATE TABLE IF NOT EXISTS Customers(
CNo integer NOT NULL,
AccNo integer,
Time varchar(50),
PRIMARY KEY (CNo));

CREATE TABLE IF NOT EXISTS ContactPersons(
Id integer NOT NULL,
Name varchar(50),
Phone integer,
PRIMARY KEY (Id));

CREATE TABLE IF NOT EXISTS Seasons(
StartDate date NOT NULL,
EndDate date NOT NULL,
PRIMARY KEY (StartDate,EndDate));

CREATE TABLE IF NOT EXISTS WebShops(
Id integer NOT NULL,
Url varchar(50),
FOREIGN KEY (Id) REFERENCES Shops (Id),
PRIMARY KEY (Id));

CREATE TABLE IF NOT EXISTS Producer(
Id integer NOT NULL,
Address varchar(50),
Name varchar(50),
PRIMARY KEY (Id));

CREATE TABLE IF NOT EXISTS Sold(
Id integer NOT NULL,
CNo integer NOT NULL,
Serial integer NOT NULL,
FOREIGN KEY (Id) REFERENCES Shops (Id),
FOREIGN KEY (CNo) REFERENCES Customers (CNo),
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
PRIMARY KEY (Id,CNo,Serial));

CREATE TABLE IF NOT EXISTS Has(
Id integer NOT NULL,
Serial integer NOT NULL,
FOREIGN KEY (Id) REFERENCES Shops (Id),
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
PRIMARY KEY (Id,Serial));

CREATE TABLE IF NOT EXISTS Has2(
Serial integer NOT NULL,
Producer_Id integer NOT NULL,
StartDate date NOT NULL,
EndDate date NOT NULL,
ContactPersons_Id integer NOT NULL,
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
FOREIGN KEY ( Producer_Id) REFERENCES Producer (Id),
FOREIGN KEY (StartDate) REFERENCES Seasons (StartDate),
FOREIGN KEY (EndDate) REFERENCES Seasons (EndDate),
FOREIGN KEY (ContactPersons_Id) REFERENCES ContactPersons (Id),
PRIMARY KEY (Serial,Producer_Id,StartDate,EndDate,ContactPersons_Id));

触发器:

CREATE TRIGGER `Seasons_before_delete` 
    AFTER DELETE ON `Seasons`
    FOR EACH ROW 
    BEGIN
    DELETE FROM seasonstart
    WHERE seasonstart.???????
    DELETE FROM seasonend
    WHERE seasonend.??????
    END

但我真的不知道。我的老师告诉我,我可以使用IFELSEIFGOTOEND?但我是在正确的轨道上吗?我现在真的很空白该做什么,所以希望有人有一个建议,我能做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:2)

在触发器中,您有2个虚拟表。

NEWOLD

显然,create触发器中没有old,而delete触发器中没有new触发器。 因此,如果您想使用发生更改的表的数据(触发器附加到的表),您可以使用这两个表。

因为这是delete触发器,您需要使用old表。

所以你的触发器看起来像这样:

CREATE TRIGGER `Seasons_before_delete` AFTER DELETE ON `Seasons`
FOR EACH ROW 
BEGIN
  DELETE FROM seasonstart
  WHERE seasonstart.seasonID = old.ID

  DELETE FROM seasonend
  WHERE seasonend.seasonID = old.ID
END

请注意,调用AFTER DELETE触发器“something_something_BEFORE”是没有意义的: - )。

进一步请注意,我不知道为什么在此触发器中需要IF,删除语句中的where已经处理了这个问题。