[英]Joining a mysql table in a query depending on the value of another cell
Please I need help, I have three mysql tables, students
, staff
and message
. 请我需要帮助,我有三个mysql表,
students
, staff
和message
。 In the message
table I have columns message_from_cat
which holds 1
if the message is from a staff and 2
if the message is from a students. 在
message
表中,我有message_from_cat
列,如果消息来自教职员工,则保留1
如果消息来自学生,则保留2
。
I also have a column message_from
which holds the id
of the sender whether staff or student. 我还有一个
message_from
列,其中包含发件人(无论是工作人员还是学生)的id
。
Now this is a pseudo code of want I want to achieve. 现在,这是我想要实现的伪代码。
select * from message left join students on message.message_from=student.student_id where message_from_cat=2
and left join staff on message.message_from=staff.staff_id where message_from=1.
Please does anyone understand my problem? 请问有人了解我的问题吗?
Remember when you left outer join you'll get all the rows back from the left ("message") table even if the id doesn't appear in the joining table ("student" or "staff"). 请记住,当您离开外部联接时,即使id未出现在联接表(“学生”或“职员”)中,您也会从左侧表(“消息”)获得所有行。
That means you can join both these tables in your FROM clause then just use a case statement or coalesce() to pick which of the joining tables has the column that you need. 这意味着您可以在FROM子句中连接这两个表,然后仅使用case语句或coalesce()来选择哪个连接表具有所需的列。
Following your pseudo : 跟随你的伪:
select
message.*,
COALESCE(staff.staff_column, student.student_column) as staff_or_student
from message
left join students
on message.message_from=student.student_id
and message.message_from_cat=1
left join staff
on message.message_from=staff.staff_id
and message.message_from_cat=2
I'm not sure of what you need. 我不确定您需要什么。 You can try
你可以试试
select * from message
left join students on message.message_from=student.student_id
where message_from_cat=2
UNION
SELECT *
FROM message
left join staff on message.message_from=staff.staff_id
where message_from=1
Or 要么
select *
from message left join students on message.message_from=student.student_id
left join staff on message.message_from=staff.staff_id
where message_from=1
AND message_from_cat=2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.