I am writing a trigger that will execute everytime a student completes an exam assignment and will update a table with what their current rank is amongst their fellow students (highest marks gives rank of 1, etc)
I started with the following query to see if I would get usable data from my student exam submissions
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;
Which returned a correct result of
++++++++++++++++++++++++
uid|rank|fname |school ++++++++++++++++++++++++ 2 | 2 |stefan|hillviewSo my student with the userID = 2 is ranked second, great, now I want to convert this into a trigger and write it to a table that stores just userID and rank
I tried to convert this to a trigger (and in so removing the hardcoded institution variable)
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$$
开发者_JAVA技巧
However, this inserts into my table
+++++++++++ uid| rank | +++++++++++ 2 | 0 |Now since it inserted uid = 2 I believe it is pulling the correct values, and I can't seem to figure out why then the userRank is 0, meaning that rownum is not incrementing.
I am trying to pinpoint why the trigger code returns the default variable value and if it is based on the nested select. Can anyone pinpoint the problem? Can you have nested selects in MySQL triggers? When I added the trigger no errors were thrown.
Try to set rownum to a default value
DECLARE rownum INTEGER DEFAULT 0
in your current trigger, the following expression
rownum = rownum + 1
will evaluate to NULL, due to the default value of rownum being null.
Additionally the = operator checks for equality (as in "x is equal to y") which means the expression will evaluate to true or false. And since rownum will never be equal to rownum+1 , your result will be false (this is why you are seeing a 0 in your resultset).
EDIT Try SELECT rownum+1 INTO rownum
精彩评论