3

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?

4

3 回答 3

4

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;
于 2012-12-21T07:28:03.663 回答
3

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
于 2012-12-21T07:34:54.477 回答
1
SELECT IF(COUNT(*) > 0, 'ok', 'not') rul FROM tb_user WHERE user_id = 1;
于 2012-12-21T07:33:54.307 回答