我的MySQL查询出错:
if not exists(select * from tb_user where user_id=1) then
select 'ok' as rul;
else
select 'not' as rul;
end if;
我的问题在哪里?
答案 0 :(得分:4)
IF语句只能用于存储的函数。您可以使用IF()函数执行所需操作,如下所示:
SELECT IF(EXISTS(select * from tb_user where user_id=1), 'ok', 'not') as rul;
答案 1 :(得分:2)
另一种方法:您也可以使用case when
Select case
when exists(select * from tb_user where user_id=1)
then 'Ok'
else 'Not'
end
;
样本表:
ID NAME
1 john
2 tim
3 jack
4 rose
查询:将列重命名为Status
Select case
when exists(select * from table1 where id=1)
then 'Ok'
else 'Not'
end as Status
;
结果:
STATUS
Ok
答案 2 :(得分:1)
SELECT IF(COUNT(*) > 0, 'ok', 'not') rul FROM tb_user WHERE user_id = 1;