mysql - 从MYSQL中的3个表中选择数据

标签 mysql sql select

我正在尝试根据 login_id 从 3 个表中获取用户名和他/她的 code_number。我有 4 个表,名为 login、tutors、institutes 和 students。

这是我的表格结构。

login table
login_id
login_type

tutor table
tutor_id
login_id
tutor_name
tutor_code

institute table
institute_id
login_id
institute_name
institute_code

student table
student_id
login_id
student_name
student_code

当用户登录到站点时,login_id 保存在 SESSION 上,然后我需要检查登录的用户类型,然后在确定用户后需要登录用户名和代码。

我的问题是如何检查哪个用户(在导师、学院、学生的情况下)已登录网站,以及如何获取其名称和代码?

希望有人帮我解决这个... 谢谢。

最佳答案

如果你想返回namecode,那么你可以在表上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 将返回第一个非空值。如果登录只能属于其中一个表,那么使用它会返回正确的值,即使用户是 tutorinstitutestudent.

如果你想在单独的列中返回它,那么你可以使用:

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/

相关文章:

php - 优化 SQL 查询

sql - 返回团队成员多次被召回的日期

php - zend 框架连接 3 个表

mysql - Sphinx 即使在关闭时也会在数据库上运行查询

php - 你知道什么好的数据库模式迁移工具吗?

mysql - 使用 Spree commerce 将 Capistrano 部署到 Ubuntu 服务器

c++ - 带有 MariaDB 的 MySQL 连接器/C++

c# - Entity Framework 日期时间错误中的存储过程

php - SQL 查询 TIMESTAMPDIFF 与 php 不工作

twitter-bootstrap - 在 Firefox 中单击选择会立即导致选项下拉菜单关闭