如何将查询结果存储到变量中?

时间:2016-08-28 15:42:01

标签: mysql sql

这是我的代码:

BEGIN     
    IF (new.edited_id IS NULL) THEN
        IF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'1000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot ask anymore";
        ELSEIF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'10000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot answer anymore";
        END IF;
    ELSE 
        IF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'100000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot edit anymore";
        END IF;
END

如您所见,那些内部IF语句的条件几乎相同。那么我该如何改进呢?我的意思是如何将该查询的结果存储到变量中,然后将该变量用作条件?

1 个答案:

答案 0 :(得分:0)

现在,您可以在if语句中使用变量condition

SET @condition := (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'1000000' > 0), 0) < 1);