2017-05-06 140 views
0

我試圖在phpMyAdmin中設置觸發器。有兩張桌子,一個父母,一個孩子。每次創建users中的新用戶時,我想要在permissions表中自動創建一行,其中(AI)生成的idusersuser_id。 (permissions.user_idusers.id一個FOREIGH鍵)SQL觸發器INSERT AFTER

用戶:

id email    password 
-------------------------------------- 
1  [email protected]  sdgsdhdfhs 
2  [email protected]  dfgsdgdfhg 
3  [email protected]  plkdfjvjvv 

權限:

index user_id  allow_read allow_write allow_delete 
------------------------------------------------------------- 
1  1   1   0    1 
2  2   1   1    1 
3  3   0   0    0 

我已經試過(沒有成功):

INSERT 
INTO permissions 
(user_id) 
VALUES 
(IDENT_CURRENT('users')) 

INSERT 
INTO permissions 
(user_id) 
VALUES 
(@@IDENTITY) 
+0

用你真正使用的數據庫標記你的問題。你有SQL Server結構,但是有一個MySQL標籤。 –

+1

如果是MySQL,可以使用'NEW.id'來訪問生成的ID。 –

+0

@GordonLinoff MariaDB/InnoDB – Rick

回答

2

要訪問導致觸發器執行的行的數據,可以使用NEWOLD別名。對於INSERT觸發器,只有NEW可用。對於DELETE觸發器,只有OLD可用。在UPDATE觸發器中,你可以同時使用兩者。它們的使用方式與表別名相同(例如,NEW.id/OLD.id)。

鑑於父和子表如下:

create table parent_table(
    id int auto_increment primary key, 
    pdata varchar(50) 
); 
create table child_table(
    id int auto_increment primary key, 
    parent_id int not null, 
    cdata varchar(50) default '', 
    foreign key (parent_id) references parent_table(id) 
); 

要插入時父行插入子行:

create trigger insert_parent 
    after insert on parent_table 
    for each row 
     insert into child_table(parent_id) 
     values (new.id); 

要刪除所有相關的子行wehen父行被刪除:

create trigger delete_parent 
    before delete on parent_table 
    for each row 
     delete from child_table 
     where parent_id = old.id; 

演示:http://rextester.com/EOW74217

不過,如果你有ON DELETE CASCADE

foreign key (parent_id) references parent_table(id) on delete cascade 

所有相關的子行會沒有觸發器被刪除定義外鍵,當你刪除父行刪除觸發器是沒有必要的。

演示:http://rextester.com/CWB43482