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

Posted

技术标签:

【中文标题】如何在一条 SQL 语句中组合两个不同的 SQL 查询?【英文标题】:How to combine two different SQL queries in one SQL statement? 【发布时间】:2020-08-24 14:41:42 【问题描述】:

我有两张桌子:

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

【问题讨论】:

这看起来不像 mysql 代码。 请看:Why should I provide an MCRE for what seems to me to be a very simple SQL query? 我将mysql标签改为sql-server并添加了nolock。 【参考方案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

【讨论】:

以上是关于如何在一条 SQL 语句中组合两个不同的 SQL 查询?的主要内容,如果未能解决你的问题,请参考以下文章

在一条 sql 语句中删除所有表、存储过程、触发器、约束和所有依赖项

如何让多个不同的SQL语句一起执行?

ERP数据库,后台为SQL。请问用啥语句能把满足某一条的值在一份报表中正数显示为负数

sql语言如何查询一条记录中含有两个关键字?

一条SQL更新语句是如何执行的

mybatis查询结果如何合并为列表