0

我有两张桌子:

Members    
Member_id | Member_user_name | Member_account_id

Members_transaction
Member_id (sender) | Member_transaction_id | Member_account_id (recipient) | Amount | from_to

所有列都有数据,但 from_to 是添加的新列。我想将发件人或收件人的用户名添加到 from_to 列中。

我曾使用以下 SQL 查询来找出发件人或收件人的用户名:

select member_user_name member_involved 
  from Members_transaction 
  left 
  join members 
    on members_transaction.member_account_id = members.member_account_id

我想在这个 SQL 查询中添加 SQL 查询:

SELECT member_transaction_id
     , mp.member_account_id
     , m.member_user_name
     , amount
     , CASE 
       -- when the amount starts with "-" such as "-100" it means paid to recipient 
       WHEN amount LIKE '-%' THEN 'Paid to' + member_involved 
       -- else it is  received from the sender
       ELSE ' Received from '+ member_involved
     END AS from_to
    FROM members_transaction MP (nolock)  
    LEFT 
    JOIN members M (NOLOCK) 
      ON M.MEMBER_ID = MP.MEMBER_ID 
     AND M.IS_USE = 1 
   WHERE MP.IS_USE = 1

由于条件不同(ON),我如何将查找发件人或收件人的 SQL 查询组合到下面的 SQL 查询中?

4

1 回答 1

1

您可以与成员一起加入两次,一次为发送者姓名,一次为接收者姓名:

SELECT member_transaction_id
 , mp.member_account_id
 , m.member_user_name
 , amount
 , CASE 
     -- when the amount starts with "-" such as "-100" it means paid to recipient 
     WHEN amount LIKE '-%' THEN 'Paid to' + M2.member_user_name 
     -- else it is  received from the sender
     ELSE ' Received from '+ M.member_user_name
   END AS from_to
 FROM members_transaction MP (nolock)  
 LEFT JOIN members M  (NOLOCK) ON M.MEMBER_ID = MP.MEMBER_ID AND M.IS_USE = 1 
 LEFT JOIN members M2 (NOLOCK) ON M2.member_account_id = MP.member_account_id AND M2.IS_USE = 1 
WHERE MP.IS_USE = 1
于 2020-08-24T15:14:45.223 回答