SQL 在多对多关系中使用名称而不是 ID

SQL name instead of ID in many to many relation

我正在尝试与数据库进行简单的聊天。所以我创建了 2 tables:

  1. Users (ID(PK), 姓名, 密码)
  2. Messages (ID(PK), senderID(FK from users), recipientID(FK from users)), text

我真的是 SQL 的菜鸟,我无法编写 return table Messages 但使用普通名称而不是 senderID 和 recipientID 的查询。此外,我没有找到 1 table 使用两次的示例,因此 JOIN 对我不起作用,或者我以错误的方式使用了它。

不确定我是否正确理解了您的问题,或者您使用的是哪个数据库,但这就是我认为您正在寻找的:

SELECT Messages.text, Users.name
FROM Messages 
inner JOIN Users
ON Messages.sender_id = Users.id
SELECT US.Name as SenderName, UR.Name as RecipientName, M.text
FROM Messages M JOIN Users US ON US.ID = M.senderID
  JOIN Users UR ON UR.ID = M.recipientID