我正在尝试根据 login_id 从 3 个表中获取用户名和他/她的 code_number。我有 4 个表,名为 login、tutors、institutes 和 students。
这是我的表格结构。
login table
login_id
login_typetutor table
tutor_id
login_id
tutor_name
tutor_codeinstitute table
institute_id
login_id
institute_name
institute_codestudent table
student_id
login_id
student_name
student_code
当用户登录到站点时,login_id 保存在 SESSION 上,然后我需要检查登录的用户类型,然后在确定用户后需要登录用户名和代码。
我的问题是如何检查哪个用户(在导师、学院、学生的情况下)已登录网站,以及如何获取其名称和代码?
希望有人帮我解决这个... 谢谢。
最佳答案
如果你想返回name
和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
将返回第一个非空值。如果登录只能属于其中一个表,那么使用它会返回正确的值,即使用户是 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
关于mysql - 从MYSQL中的3个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14816128/