如果第一个结果为null,如何运行第二个SQL查询

时间:2013-09-02 14:03:40

标签: mysql sql if-statement case

我正在围绕这个圈子,并希望有人可以了解如何在第一个返回null时运行第二个查询。

select employee, date, workingrule
case when workingrule is null
then 1 else (select employeenumber, bonusrule from employeelist)
end
from employeedetails

基本上,如果工作规则是空白的,我想找到员工奖金。 非常感谢任何指导的帮助。 感谢名单

2 个答案:

答案 0 :(得分:2)

这个适用于SQL Server(因为使用isnull,但可以将其更改为任何特定于RDBMS的查询):

select
   ed.employee, ed.date,
   isnull(ed.workingrule, el.bonusrule) as [rule]
from employeedetails as ed
    left outer join employeelist as el on el.employeenumber = ed.employeenumber 

或者如果你想要两者(应该适用于任何RDBMS):

select
   ed.employee, ed.date,
   ed.workingrule,
   case when ed.workingrule is null then '1' else el.bonusrule end as bonusrule
from employeedetails as ed
    left outer join employeelist as el on el.employeenumber = ed.employeenumber 

答案 1 :(得分:0)

select 
  employee, date, Coalesce(workingrule, BonusRule) as Rule 
from 
  employeedetails ed
  left join employeelist el on 
    el.employeenumber = ed.employeenumber