我正在寫一個觸發器,每次學生完成一項考試任務時都會執行,並將更新一張表,其中包括他們當前的成績等級(最高分數等於1等)MySQL觸發變量和嵌套選擇
我開始用下面的查詢,看看是否我會從我的學生考試提交
SET @rownum := 0;
SET @school := 'hillview';
SELECT userID, rank, firstname, institution
FROM (
SELECT @rownum := @rownum + 1 AS rank, userID, firstname, institution FROM(
SELECT userID, sum(marks), firstname, institution
FROM competition_history
WHERE institution = @school
GROUP BY userID
ORDER BY marks DESC) as inner_rank
) as r
WHERE userID = 2;
哪個返回的
一個正確的結果得到有用的數據+++++++++++ +++++++++++++
uid |等級| fname |學校
++++++++++++++++++++++++
2 | 2 |斯特凡|曉嵐
所以我的學生與用戶ID = 2排名第二,偉大的,現在我想將其轉換成一個觸發,並將其寫入到一個表,用於存儲只是用戶ID和排名
我試圖將其轉換爲一個觸發(因而去除硬編碼制度變量)
DELIMITER $$
DROP TRIGGER IF EXISTS CallRankProc;
CREATE TRIGGER callRankProc AFTER INSERT
ON competition_history
FOR EACH ROW
BEGIN
DECLARE rownum INTEGER DEFAULT 0;
DECLARE userRank INTEGER;
SELECT _rank into userRank
FROM (
SELECT rownum = rownum + 1 AS _rank, userID, firstname, institution FROM(
SELECT userID, sum(marks), firstname, institution
FROM competition_history
WHERE institution = NEW.institution
GROUP BY userID
ORDER BY marks DESC) as inner_rank
) as r
WHERE userID = NEW.userID;
INSERT INTO `student_ranks`(`userID`,`rank`) VALUES (NEW.userID,userRank)
ON DUPLICATE KEY UPDATE rank = userRank;
END$$
然而,這種插入到我的表
+++++++++++
UID |等級|
+++++++++++
2 | 0 |
現在,因爲它插入了uid = 2我相信這是拉正確的值,我似乎無法弄清楚爲什麼然後userRank爲0,這意味着rownum不遞增。
我想找出爲什麼觸發器代碼返回默認變量值,如果它是基於嵌套選擇。任何人都可以指出問題嗎?你能在MySQL觸發器中嵌套選擇嗎?當我添加觸發器時不會引發錯誤。
也usedDECLARE ROWNUM整數缺省值0 –