2014-08-31 59 views
0

所以我創建了一個觸發器來更新插入的另一個表,沒有發現錯誤和觸發器存在(獲取列在SHOW TRIGGERS,但插入到後,沒有更新到另一個表一個MySQL觸發器將不會工作,沒有錯誤

觸發:

CREATE TRIGGER setmapsquare AFTER INSERT ON users 

FOR EACH ROW 
UPDATE map SET player_id = NEW.player_id WHERE map_id = NEW.startsquare; 

它不引發錯誤,所以我現在不應該怎麼做:/

編輯:還插入發生在這裏:

$q = $DBC -> prepare(" 
    INSERT INTO 
     users 
    (username, password, email, startsquare) 
    VALUES (?, ?, ?, (SELECT map_id FROM map WHERE player_id IS NULL ORDER BY RAND() LIMIT 1));"); 

插入的行1, 'Testjuuser', '2bd7fc520207eabc4026989728def05b541a863e', '[email protected]', 38, 2014-08-31 09:20:28, 0, 0

和MAP_ID 38仍然NULL作爲其player_id

+0

它看起來像你的WHERE子句過濾掉映射表中的所有行。 – VMai 2014-08-31 15:32:30

+0

這很奇怪,因爲在新的行中,startquare被清楚標記。並且該值存在於地圖表中,因爲我選擇了它:'$ q = $ DBC - >準備(「 INSERT INTO users (username,password,email,startsquare) VALUES(?,? ?,(SELECT map_id FROM map WHERE player_id is NULL ORDER BY RAND()LIMIT 1));「);'' – Limiter 2014-08-31 15:35:48

+1

我建議激活一般查詢日誌來調試這個問題 – VMai 2014-08-31 15:39:34

回答

1

由問題中所描述的行爲不能被再現。該INSERT聲明將失敗,錯誤消息:

Error Code: 1442. Can't update table 'map' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

步驟以重現此:

CREATE TABLE users (
    player_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    username VARCHAR(20), 
    password VARCHAR(80), 
    email VARCHAR(260), 
    startsquare INT 
); 

CREATE TABLE map (
    map_id INT, 
    player_id INT 
); 

插入一些值表映射

INSERT INTO map (map_id, player_id) VALUES 
(37, NULL), 
(38, NULL), 
(39, NULL); 

創建觸發器

DELIMITER // 
CREATE TRIGGER setmapsquare AFTER INSERT ON users 
FOR EACH ROW 
UPDATE map SET player_id = NEW.player_id WHERE map_id = NEW.startsquare; 
// 
DELIMITER ; 

試試這個插入

INSERT INTO users (username, password, email, startsquare) VALUES 
(
    'Testjuuser', 
    '2bd7fc520207eabc4026989728def05b541a863e', 
    '[email protected]', 
    (SELECT map_id FROM map WHERE player_id IS NULL ORDER BY RAND() LIMIT 1) 
); 

,並得到上述錯誤消息,see this demo

注:你必須註釋掉38和前選擇刪除破折號。

雖然如預期的那樣硬編碼38將處理:

INSERT INTO users (username, password, email, startsquare) VALUES 
(
    'Testjuuser', 
    '2bd7fc520207eabc4026989728def05b541a863e', 
    '[email protected]', 
    38 
); 

結論

無論是實際觸發聲明這並不是說在這個問題顯示或有錯誤,但隨後的INSERT應完全失敗。要檢查觸發語句一個可以使用下面的對抗INFORMATION_SCHEMA查詢:

SELECT 
    trigger_schema,   -- the database, 
    event_object_table,  -- table 
    action_timing,   -- should be 'after' 
    event_manipulation,  -- should be 'INSERT' 
    action_statement  -- the actual code 
FROM 
    INFORMATION_SCHEMA.TRIGGERS 
WHERE 
    trigger_name = 'setmapsquare'; 

action_statement的內容是在我的情況

UPDATE map SET player_id = NEW.player_id WHERE map_id = NEW.startsquare 
+0

我會接受尊重這種徹底的答案,但它不會像我這樣做。我會稍微改變一下邏輯,所以我不必爲此使用觸發器。謝謝你的時間:) – Limiter 2014-08-31 18:00:18