Reputation: 10021
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
Upvotes: 0
Views: 89
Reputation: 1269703
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);
Upvotes: 1