简体   繁体   中英

How to use alias in mysql triggers?

I'm am trying to create this mysql trigger:

DELIMITER // 
CREATE TRIGGER checkcollision2 AFTER UPDATE ON projectiles p1 
    FOR EACH ROW 
    BEGIN 
        IF (SELECT count(*) FROM players p WHERE p.wolf=1 AND NEW.x>=p.x AND NEW.x<=p.x+25 AND NEW.y>=p.y AND NEW.y<=p.y+25) > 0 THEN 
            DELETE FROM projectiles p2 WHERE p1.id=p2.id;
        END IF; 
    END;// 
DELIMITER ; 

But this isn't working, as its getting a syntax error. I'm not sure if its because I'm using an alias names for the tables. I am doing that because, if the if statement is true, then I want to delete the current updated row that the trigger started on. I think I could do that by doing a delete from the same table, where the id is the same, but if I don't use alias, then all rows from this table would be deleted.

Does anyone see whats wrong here?

Alias names on identifies at trigger signature level is not supported and hence is incorrect.
Instead you can define alias within the trigger body if required.

And as you want to perform a delete operation based on a condition, you can make use of NEW to compare with a specific row-column value. Current where clause WHERE p1.id=p2.id will delete ALL rows from the table, which is unsafe.

Change your trigger definition as below:

DELIMITER // 

DROP TRIGGER IF EXISTS checkcollision2 //

CREATE TRIGGER checkcollision2 AFTER UPDATE ON projectiles 
    FOR EACH ROW 
    BEGIN 
        DELCARE match_count INT DEFAULT 0;
        SELECT count(*) INTO match_count
          FROM players p 
         WHERE p.wolf = 1
           AND NEW.x BETWEEN p.x AND ( p.x + 25 )
           AND NEW.y BETWEEN p.y AND ( p.y + 25 )

        IF match_count > 0 THEN
            DELETE FROM projectiles WHERE id = NEW.id;
        END IF; 
    END; 

    // 

DELIMITER ; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM