简体   繁体   English

postgres在“ main”表上联接“ other”表,该表对“ other”表有2个引用

[英]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: 在访问数据库之前,我使用登录用户的用户ID来获取登录用户的所有消息:

GET /messages?userId=some-id

my sql query: 我的SQL查询:

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: 我想我知道如何进行联接以获取用户(如果这是他的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): 基本上,我想要消息记录的所有数据以及两个关联用户的所有数据(json,不确定如何将其表示为列):

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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