如果你想返回name
and code
,那么你可以JOIN
在桌子上。您的查询将与此类似:
select l.login_id,
l.login_type,
coalesce(t.tutor_name, i.institute_name, s.student_name) Name,
coalesce(t.tutor_code, i.institute_code, s.student_code) Code
from login l
left join tutor t
on l.login_id =t.login_id
left join institute i
on l.login_id = i.login_id
left join student s
on l.login_id = s.login_id
将COALESCE
返回第一个非空值。如果登录名只能属于其中一个表,那么即使用户是 a或tutor
,使用它也会返回正确的值。institute
student
如果您想在单独的列中返回它,那么您可以使用:
select l.login_id,
l.login_type,
t.tutor_name,
t.tutor_code,
i.institute_name,
i.institute_code,
s.student_name,
s.student_code
from login l
left join tutor t
on l.login_id =t.login_id
left join institute i
on l.login_id = i.login_id
left join student s
on l.login_id = s.login_id