我有3张 table .. 说。
- users
(id,name,role_id(FK 角色)
- 工作人员
(id,姓名,user_id(外线用户)
- 角色
(id,名称)
- 学生
(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:staff
和 role_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/