如果语法错误

IF syntax error

我在遵循 IF 语法的 MySQL 指南时遇到语法错误。

我的查询是:

if 0=0 then select 'hello world'; end if;

从逻辑上讲,这应该 select 'hello world',但我却得到

ERROR 1064 (42000): 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 (0=0) then select 'hello world'' at line 1
ERROR 1064 (42000): 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 'end if' at line 1

您的查询仅在存储的 procedure/function 上下文中有效。 请参阅 there 以供参考。

If 语句在一般 SQL 流程中不受支持。它只能在函数或过程中使用。但是您可以通过以下方式使用它

use my_db;
delimiter #
create procedure xyz()
 begin
   IF 0=0 then select 'hello world';
 end if;
end#

像这样使用 if 语句仅在存储过程或函数中有效。

您可能喜欢使用if()函数,然后您可以使用:

select IF(0=0, 'hello world','');