简体   繁体   中英

Two Foreign Keys Refer same column of another table?

I have two relations like this, user(user_id, user_name) messages(sender,reciever,time,message) in here both sender and reciever refers user_id of the user table. I need to write a query to get sender's user_name recievers user_name , message.

You need to JOIN with the referring table twice like

select u1.user_name as Sender,
u2.user_name as Receiver,
m.message
from messages m
join user u1 on m.sender = u1.user_id
join user u2 on m.receiver = u2.user_id;

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