Mysql sql如果存在简单语法错误

Mysql sql如果存在简单语法错误,mysql,sql,Mysql,Sql,我经常会遇到这种语法错误,但与其他示例相比,我没有发现任何错误 if EXISTS (select 1 from City where name = 'Perth') THEN Print 'Record exits - Update' ELSE Print 'Record doesn''t exist - Insert' 我发现错误: #1064 - You have an error in your SQL syntax; check the manual that correspo

我经常会遇到这种语法错误,但与其他示例相比,我没有发现任何错误

if EXISTS (select 1 from City where name = 'Perth')
THEN  Print 'Record exits - Update'
ELSE  Print 'Record doesn''t exist - Insert' 
我发现错误:

#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 EXISTS (select
1 from City where name = 'Perth') THEN Print 'Record e' at line 1

我在zend cloud和普通的phpmyadmin mysql 5上都得到了这个结果,这实际上不是一个有效的mysql查询。看起来您正试图将SQL与根据查询是否存在显示输出的方式混合在一起。您可以使用此选项返回SQL中是否存在Perth:

SELECT EXISTS(SELECT 1 FROM City WHERE name = 'Perth')
这将返回1或0,然后可以使用服务器端脚本对其进行解析。它之所以会给您一个语法错误,是因为MySQL IF语句的形式为IFcondition,,没有使用THEN或ELSE,这在编程语言中很常见。此外,MySQL没有显式的PRINT语句,但是您可以使用SELECT来完成上面所述的任务。注意,如果结果不返回任何内容,我们可以删除EXISTS,因为将暗示为False:

SELECT IF(
      (SELECT 1 FROM City WHERE name = 'Perth'),
      (SELECT 'Record exists - update'),
      (SELECT 'Record does not exist - Insert')
)

另一种方法:使用分组函数将始终返回记录。如果没有可操作的记录,group by函数的结果将为空。你可以把它作为一种决策机制

postgres=# create table city(name text);
CREATE TABLE
postgres=#
postgres=# select COALESCE( max('Record exists - Update'), 'Record doesn''t exist - Insert' ) as state
postgres-#   from city
postgres-#   where name = 'Perth';
             state
-------------------------------
 Record doesn't exist - Insert
(1 row)


postgres=#
postgres=# insert into city values('Perth');
INSERT 0 1
postgres=#
postgres=# select COALESCE( max('Record exists - Update'), 'Record doesn''t exist - Insert' )  as state
postgres-#   from city
postgres-#   where name = 'Perth';
         state
------------------------
 Record exists - Update
(1 row)

您需要使用“选择”而不是按以下方式打印

select IF((select 1 from city where name='Perth'),
'Record exits - Update','Record does not exist - Insert');
。下面显示了IF在select语句中的用法

IF((select 1 from city where name='Perth'),
'Record exits - Update','Record does not exist - Insert');
IF包含两条消息

第一个:“记录退出-更新”第二个:“记录不存在-插入”


如果从城市中选择1,则会打印第一条消息,其中name='Perth'的某些结果与存在的结果相同,否则您将收到第二条消息

嘿,只是想知道您使用的设置是什么,因为即使我将print语句更改为select,这对我也不起作用ones@Tommy. 你是对的。我以前说过的使用if的方法是用于存储过程。你可以看到我编辑过的答案。希望它能解释if在select语句中的用法。