Tanning system with Stored Procedure

Asked

Viewed 29 times

0

I’m trying to make a stored Precedent for a simple likes system, my table is organized like this:

  • Likes
    • id INT(11) - Auto Increment
    • post INT(11) - foreign key (id - post)
    • user INT(11) - foreign key (id - users)
  • Users
    • id INT(11) - Auto Increment
    • name VARCHAR(15)
  • Post
    • id INT(11) - Auto Increment
    • contents VARCHAR(200)

My logic I’m trying to apply:

  • @value: 1 = liked, 2 = not liked
  • @post: id of the post
  • @user: user id

1.If there is no value matching the user id and the post id it creates one and adds the value to the type.

2.If it exists and the type is equal to the value sent it deletes.

3.If it exists and the type is different from the value, it updates.

CREATE DEFINER=`root`@`localhost` PROCEDURE `Teste`(
    IN `@valor` INT,
    IN `@post` INT,
    IN `@user` INT
)
IF NOT EXISTS (SELECT * FROM curtida WHERE user = `@user` AND  post = `@post`)
    BEGIN
        INSERT INTO curtida (tipo, post, user) VALUES (`@valor`, `@post`, `@user`);
    END
ELSE    
    IF (SELECT tipo FROM curtida WHERE user = `@user` AND post = `@post`) = `@valor`
        BEGIN
            DELETE FROM curtida WHERE user = `@user` AND post = `@post`;
        END
    ELSE
        BEGIN
            UPDATE FROM curtida SET tipo = `@valor` WHERE user = `@user` AND post = `@post`;
        END

In all IF and END are showing syntax error and I’m already a little lost with this kkk, I could do in php but it would be a great loss of performance because I would use various queries and comparisons

1 answer

1


The main mistake would be the BEGIN and END who was using us IF.

You can see the documentation here.

As it turned out:

 DELIMITER $$
 CREATE DEFINER = `root`@`localhost` PROCEDURE `Teste`(IN `@valor` INT, IN `@post`  INT,IN `@user`  INT)
 BEGIN
     IF NOT EXISTS(SELECT * FROM curtida WHERE user = `@user` AND post = `@post`) THEN
         INSERT INTO curtida (tipo, post, user) VALUES (`@valor`, `@post`, `@user`);
     ELSEIF ((SELECT tipo FROM curtida WHERE user = `@user` AND post = `@post`) = `@valor`) THEN
             DELETE FROM curtida WHERE user = `@user` AND post = `@post`;
     ELSE
         UPDATE curtida SET tipo = `@valor` WHERE user = `@user` AND post = `@post`;
     END IF;
 END $$
 DELIMITER ;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.