如何在一个 SQL 语句中组合两个不同的 SQL 查询?

How to combine two different SQL queries in one SQL statement?

我有两个表,它们是:

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查询?

您可以加​​入两次成员,一次用于发送者姓名,一次用于接收者姓名:

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