找到SQL IF值,ELSE做其他事情

时间:2017-10-03 11:09:32

标签: mysql

问题

如果在表雇主中找到userID,我怎样才能得到一个简单的表userType = employeeuserType = employer

试图做

通过以下代码,我可以获得一个回报,即当他是一个雇主时,这个用户是雇主,当他不是我什么也得不到时。

SELECT (CASE WHEN (userID IS NOT NULL) THEN 'employer' ELSE 'employee' END) AS 'userType' FROM tblEmployer WHERE userID = 401

还尝试使用if语句

IF EXSISTS (SELECT userID FROM tblEmployer WHERE userID = 401) 
IF ((SELECT COUNT(*) FROM tblEmployer WHERE userID = 401) > 0) ELSE ...

但是这会给Assignment type not recognized. (near "IF" at position 0)

1 个答案:

答案 0 :(得分:1)

如果要准确返回一行,请在select子句中使用聚合或子查询:

select (case when exists (select 1
                          from tblEmployer e
                          where e.userId = 401
                         )
             then 'employer' else 'employee'
        end) as userType

可替换地:

select (case when count(*) > 0 then 'employer' else 'employee' end) as userType
from tblEmployer e
where e.userId = 401;