简体   繁体   中英

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 . 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.

I also have a column message_from which holds the id of the sender whether staff or student.

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").

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM