简体   繁体   中英

postgres join “other” table on “main” table that has 2 references to “other” table

I have the following db schema:

messages
  senderId: user
  receiverId: user

I'm trying to fetch all messages with both the sender user and the receiver user records attached but I'm not sure how to go about doing that. Before hitting the database, I fetch all messages for the logged in user by using his user id:

GET /messages?userId=some-id

my sql query:

SELECT * from messages
WHERE senderId=userId
OR receiverId=userId

I think I know how to do a join to get the user if it's his id:

SELECT messages.*, users.* from messages
INNER JOIN users ON messages.senderId = userId OR messages.receiverId = userId
WHERE senderId=userId
OR receiverId=userId

but I don't know how to join the 'other' user for the message. I also don't know if the query I'm attempting above will work because I haven't tested it yet.

Thank you for the help

Basically, I want all the data for the message record, and all the data for the 2 associated users (json, not sure how to express this as a column):

message: {
 title: 'message title',
 body: 'message body....',
 sender: {
  name: '',
  email: '',
  etc...
 },
 receiver: {
  name: '',
  email: '',
  etc...
 }
}

hope that helps

Are you just trying to get the two names?

select m.*, um.name as sender_name, ur.name as receiver_name
from messages m join
     users us
     on m.senderid = us.userid join
     users ur
     on m.receiverid = ur.userid
where @userid in (m.sender_id, m.receiverid);

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