确定子表的类型

时间:2015-04-01 08:29:41

标签: mysql database

问题: 我已经模拟了mySQL表来模拟表之间的继承,例如:

Example model

有没有什么好方法可以查询员工并输出他们的员工类型?

所需的输出是:

id   name                             salary     type
------------------------------------------------------------
1    John Doe                         2000       executive
2    Jane Doe                         1000       manager
3    Nick Carter                      500        intern

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您可以使用一个表来维护员工的类型,但在这种情况下,您可以执行

select 
e.* ,
case 
  when i.employee_id is not null then 'intern'
  when m.employee_id is not null then 'manager'
  when ex.employee_id is not null then 'executive'
end as `type` 
from employee e 
left join intern i on i.employee_id = e.id
left join manager m on m.employee_id = e.id
left join executive ex on ex.employee_id = e.id