MySQL 'if exists' error

可紊 提交于 2019-12-13 15:52:37

问题


I got a error in my MySQL query:

if not exists(select * from tb_user where user_id=1) then
     select 'ok' as rul;
else
     select 'not' as rul;
end if;

Where's my problem?


回答1:


Another method: You may also use case when

Select case
when exists(select * from tb_user where user_id=1)
then 'Ok'
else 'Not'
end
;

* SQLFiddle Demo

Sample table:

ID  NAME
1   john
2   tim
3   jack
4   rose

Query: renamed the columns as Status

Select case
when exists(select * from table1 where id=1)
then 'Ok'
else 'Not'
end as Status
;

Results:

STATUS
Ok



回答2:


The IF statement can only be used in stored functions. You can do what you want with the IF() function, as follows:

SELECT IF(EXISTS(select * from tb_user where user_id=1), 'ok', 'not') as rul;



回答3:


SELECT IF(COUNT(*) > 0, 'ok', 'not') rul FROM tb_user WHERE user_id = 1;


来源:https://stackoverflow.com/questions/13985950/mysql-if-exists-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!