无法执行查询,如果then语句

wrrgggsh  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(284)

我不能执行如下查询:我不知道为什么:

IF(NOT EXISTS(SELECT accountId FROM test_account WHERE content = '123')) THEN
    INSERT INTO test_account (content) VALUES ('123');
END IF;
SELECT accountId FROM test_account WHERE content = '123' LIMIT 1;

收到错误:


# 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF(NOT EXISTS(SELECT accountId FROM test_account WHERE content = '123')) THEN INSE' at line 1

编辑:
我试着先写程序:

CREATE FUNCTION getTestAccount(var_c VARCHAR(20)) RETURNS INT
BEGIN
IF NOT EXISTS(SELECT accountId FROM test_account WHERE content = var_c)
THEN
    INSERT INTO test_account (content) VALUES (var_c);
END IF;
RETURN (SELECT accountId FROM test_account WHERE content = var_c LIMIT 1);
END;

我试过了 THEN 没有。。。
甚至不能查询简单的内容:

CREATE FUNCTION getVar(var INT) RETURNS INT
BEGIN
RETURN var;
END;
3ks5zfa0

3ks5zfa01#

你的函数代码看起来不错。我想知道您是否忘记在进入函数之前设置分隔符,以防止mysql被 ; 函数中的s,即。

DELIMITER //
CREATE FUNCTION getTestAccount(var_c VARCHAR(20)) RETURNS INT
BEGIN
    IF NOT EXISTS(SELECT accountId FROM test_account WHERE content = var_c) THEN
        INSERT INTO test_account (content) VALUES (var_c);
    END IF;
    RETURN (SELECT accountId FROM test_account WHERE content = var_c LIMIT 1);
END //
DELIMITER ;
tjjdgumg

tjjdgumg2#

不清楚您正在使用的代码的上下文。。但您也可以尝试这样的插入选择

INSERT INTO test_account (content) 
    SELECT '123' 
    FROM test_account 
    WHERE content = '123' 
    AND   NOT EXISTS(SELECT accountId 
              FROM test_account WHERE content = '123') 
    LIMIT 1;

相关问题