触发器不允许我更新

时间:2018-04-30 15:13:46

标签: mysql sql triggers

我有以下触发器:

  delimiter |
CREATE TRIGGER DES1actualizarConsultaR_update
AFTER UPDATE ON ranking
FOR EACH ROW
BEGIN
UPDATE player P,
    (SELECT 
        J.player_id AS jugador_id,
            SUM(ranking_points) AS PuntosTotales
    FROM
        player J
    INNER JOIN ranking R ON R.player_id = NEW.player_id
    GROUP BY J.player_id) AS TD 
SET 
    P.totalPuntos = TD.PuntosTotales
WHERE
    P.player_id = TD.jugador_id;

UPDATE player P,
    (SELECT 
        J.player_id AS JnumUno, COUNT(*) AS NumVeces1
    FROM
        player J
    INNER JOIN ranking R ON R.player_id = NEW.player_id
    WHERE
        R.ranking = '1'
    GROUP BY J.player_id) AS TD 
SET 
    P.vecesNum1 = TD.NumVeces1
WHERE
    P.player_id = TD.JnumUno;

END |

我正在尝试执行此更新:

UPDATE ranking 
SET 
    ranking_points = (ranking_points + 10)
WHERE
    player_id IN (SELECT 
            P.player_id
        FROM
            player P,
            tourney T,
            tmatch M
        WHERE
            T.tourney_name LIKE 'Madrid%'
                AND T.tourney_date BETWEEN '2017-01-01' AND '2018-12-31'
                AND (M.round = 'F' OR M.round = 'SF')
                AND P.player_id = M.winner_id
                AND M.tourney_id = T.tourney_id);

但我有这个错误:

  

错误代码:1442。无法更新已存储的表'播放器'   函数/触发器,因为它已被调用的语句使用   这个存储的函数/触发器。

如何进行更新查询?

我正在使用MYSQL。

1 个答案:

答案 0 :(得分:0)

这是因为您在TRIGGER的UPDATE语句中的ranking表上有一个联合。

即使您没有更新ranking表本身,MySQL也不喜欢它。

你必须首先通过执行独立的SELECT查询来计算玩家的点数,将这些点保存在变量中,然后在player表的更新中使用它,而不参考ranking

以下是这个想法:

 delimiter |
CREATE TRIGGER DES1actualizarConsultaR_update
AFTER UPDATE ON ranking
FOR EACH ROW
BEGIN

    DECLARE vPuntosTotales INT;
    DECLARE vNumVeces1 INT;

    SELECT SUM(ranking_points) AS PuntosTotales INTO vPuntosTotales 
    FROM ranking  
    WHERE player_id = NEW.player_id;


    UPDATE player SET totalPuntos = vPuntosTotales WHERE player_id = NEW.player_id;


    -- NOT SURE IF THIS ONE IS CORRECT
    SELECT COUNT(*) AS NumVeces1 INTO vNumVeces1 
    FROM ranking R 
    WHERE R.ranking = '1' AND R.player_id = NEW.player_id;  


    UPDATE player SET vecesNum1 = vNumVeces1 WHERE player_id = NEW.player_id;

END |

你应该检查我的查询,因为我不完全知道你的表结构,我的SELECT可能是错的,特别是在第二个