MySQL基于条件的多重连接

标签 mysql sql node.js database

我有3张 table .. 说。

  1. users(id,name,role_id(FK 角色)
  2. 工作人员(id,姓名,user_id(外线用户)
  3. 角色(id,名称)
  4. 学生(id,name,user_id(FK to users)

我需要这样的结果:
当用户是学生(roleid=5)时,我需要加入学生表并获取学生详细信息。或者当用户是员工(role_id=3)时,我只需要从员工表中获取详细信息并显示。怎么可能呢。 我编写了一个查询,该查询与 2 个表进行左连接,但它显示了不参与本例的其他表。

在这里分享一下我遇到的事情

    select * 
      from users u 
     JOIN roles r on u.role_id=r.id 
left join staff st on st.user_id=u.id 
left join students s on s.user_id=u.id 
    where u.id=11068

role_id=3:staffrole_id=5 Student 类似于 C 编程中的 switch case


我正在寻找的是

switch(role_id){ case 3: JOIN with students table;return;case 5:JOIN with staff table;return;}

最佳答案

您可以在教职员工和学生的联接中使用这些 role_id。

由于教职员工姓名或学生姓名为空,您可以使用 COALESCE 仅获取 1 个姓名。

select 
 u.name as user_name, 
 u.role_id,
 r.name as role_name,
 COALESCE(sta.name, stu.name) AS name
FROM users u 
LEFT JOIN roles r ON r.id = u.role_id
LEFT JOIN staff sta ON (sta.user_id = u.id AND u.role_id = 3)
LEFT JOIN students stu ON (stu.user_id = u.id AND u.role_id = 5)
WHERE u.id = 11068

但我认为连接中不需要这些额外的规则。

我假设你可以说某人是学生,如果他们在“学生”中。
当他们处于“工作人员”状态时,还有工作人员。
与 role_id 无关。

在 SQL 中,您也可以使用 CASE 作为开关。

select 
 u.name as user_name, 
 u.role_id,
 r.name as role_name,
 (CASE u.role_id
  WHEN 3 THEN sta.name
  WHEN 5 THEN stu.name
  END) AS name
FROM users u 
LEFT JOIN roles r ON r.id = u.role_id
LEFT JOIN staff sta ON sta.user_id = u.id
LEFT JOIN students stu ON stu.user_id = u.id
WHERE u.id = 11068

关于MySQL基于条件的多重连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179526/

相关文章:

mysql - 触发器正在复制数据

mysql - 在 MySQL 中表示票价表

mysql - 创建 View 和性能

node.js - 删除所有事件发射器监听器(最新的除外)

mysql - 在 MYSQL Workbench 中声明语法错误

php - 将 mysql 数据库与 xml 文件同步

mysql - 查找每个客户的所有销售额

mysql - 在同一张表上有两个连接的条件 WHERE

node.js - Ansible 和 npm 安装失败并显示 "rc -9"。这是什么意思?

node.js - 在 Visual Studio 2017 中更新 Node 版本