MySQL中IF语句的正确语法是什么? [英] What is the right syntax of IF statement in MySQL?

查看:768
本文介绍了MySQL中IF语句的正确语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小而简单的MySQL代码。但每当我运行它时,我都会收到错误#1064。你能告诉我这里的错误是什么吗?

I have a small and simple MySQL code. But whenever I run it, I get error #1064. Can you tell me what is my mistake here?

IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
    BEGIN
        SELECT * FROM tbl_cities;
    END
END IF

我还使用了一些其他条件如下,但我又得到了一个错误。

I also used some other conditions like the below one, but again I got an error.

IF (1=1) THEN
    BEGIN
        SELECT * FROM tbl_cities;
    END
END IF

我真正想做的是这样的事情:

What I actually want to do is something like this:

IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
    BEGIN
        UPDATE ...
    END
ELSE
    BEGIN
        INSERT ...
    END
END IF


推荐答案

如果是您正在编写的程序,请尝试:

If it is a procedure you're writing you should try:

BEGIN
    IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
        SELECT * FROM tbl_cities;
    END IF
END

如果是查询, BEGIN END 此处无关。

If it is a query, BEGIN and END have nothing to do here.

编辑

好吧,没有更多要说的, IF((SELECT COUNT(id)FROM tbl_states)> 0)那么SELECT * FROM tbl_cities; END IF 根本不尊重基本的MySQL SELECT语句

Well, there is not really more to say, IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN SELECT * FROM tbl_cities; END IF is simply not respecting the basic MySQL SELECT statement.

你应该从 SELECT ......等开始......

You should start with SELECT... etc...

这篇关于MySQL中IF语句的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆