SQL 中可以使用什么单行查询来显示交易历史中的用户名?

What single line query can be used in SQL to display usernames from transaction history?

我有两个 table:用户和交易

Table结构:

用户: 用户身份 用户名 密码 电子邮件地址

交易:

    TRANSACTIONID
    AMOUNT
    EXPENSEID
    USERID_1 (refers to user who owes money)
    USERID_2 (refers to user who is owed money)
    STATUS

我想显示交易 table 中 userid_1 和 userid_2 的用户名,以及 userid_1 或 userid_2 中的金额和状态匹配特定用户(比如用户 7)

  1. 只需与用户 table 加入交易 table 两次即可获取 userid_1 和 userid_2
  2. 的名称
  3. 包含一个 WHERE 子句以匹配您要查看的用户(比如用户 7)

db<>fiddle

SELECT u1.username AS userid_1_name, u2.username AS userid_2_name, t.amount, t.status
FROM transactions t 
JOIN users u1 ON u1.userid = t.userid_1
JOIN users u2 ON u2.userid = t.userid_2
WHERE t.userid_1 = 7 OR t.userid_2 = 7;