无法使用IF ... THEN语句执行查询

时间:2018-09-06 11:17:22

标签: mysql

我无法执行查询,例如:而且我也不知道为什么:

const Routes = () => (
<BrowserRouter basename="http://localhost/hositng/react" >
    <Switch>
        <Route exact path='/' component={Login} />
        <Route path='/login' component={Login} />
        <Route path='/home' component={Home} />
        <Route path='/contact' component={Contact} />
    </Switch>
</BrowserRouter>);

收到错误:

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

2 个答案:

答案 0 :(得分:0)

无法清除您正在使用代码的上下文..但您也可以尝试以这种方式进行插入选择

    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;

答案 1 :(得分:0)

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

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 ;