mysql if else多查询语句

tnkciper  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(480)

我是mysql新手,我想在查询中使用if else语句

IF (EXISTS (SELECT user_token 
            FROM upvotes 
            WHERE user_token ="user_token" AND comment_token = "comment_token"
           )
   ) 
THEN (DELETE 
      FROM upvotes 
      WHERE user_token = 'user_token' AND comment_token = "comment_token"
     ) 
     AND 
     (UPDATE comments 
      SET upvote = upvote +1 
      WHERE token = "comment_token" 
     ) 
ELSE (INSERT INTO upvotes(user_token,comment_token 
      VALUES('user_token','comment_token'
     ) 
     AND 
     (UPDATE comments 
      SET upvote = upvote -1 
      WHERE token = "comment_token"
     ) 
END IF

但是这个错误发生了 Unrecognized statement type. (near "IF" at position 0) SQL query: Copy Documentation

but5z9lq

but5z9lq1#

在普通的sql查询中不能这样做。必须在函数或存储的pricedure中执行此操作

DROP procedure IF EXISTS `new_procedure`;

DELIMITER $$
USE `testdb1`$$
CREATE PROCEDURE `new_procedure` ()
BEGIN
IF (EXISTS (SELECT user_token FROM upvotes WHERE user_token ="user_token" AND comment_token = "comment_token")) THEN 
    DELETE FROM upvotes WHERE user_token = 'user_token' AND comment_token = "comment_token";
    UPDATE comments SET upvote = upvote +1 WHERE token = "comment_token" ;
ELSE 
    INSERT INTO upvotes(user_token,comment_token) VALUES('user_token','comment_token');
    UPDATE comments SET upvote = upvote -1 WHERE token = "comment_token";
END IF;
END$$

DELIMITER ;

你会撞到:

call new_procedure();

相关问题