由問題中所描述的行爲不能被再現。該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
它看起來像你的WHERE子句過濾掉映射表中的所有行。 – VMai 2014-08-31 15:32:30
這很奇怪,因爲在新的行中,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
我建議激活一般查詢日誌來調試這個問題 – VMai 2014-08-31 15:39:34