SQL 不存在查询

SQL Not Exists query

我在 sql 查询中集成 NOT EXISTS 时遇到问题。让我详细解释一下这个问题 我有四个 tables:branch_details、交易、branch_order_relation 和 branch_pincode_relation.

这是我的 SQL 查询

   private static final String SELECT_ORDERS_BY_BRANCH = 
"select transaction_id,source_id,destination_id 
from transactions,branch_pincode_relation,branch_details,branch_order_relation 
where branch_details.branch_email = ? 
and branch_details.branch_id = branch_pincode_relation.branch_id 
and branch_pincode_relation.origin_pincode = transactions.start_pin 
and transactions.parent_transaction_id IS NOT NULL 
and transactions.order_status = "+JiffieConstants.PAYMENT_SUCCESS;

branch_order_relation 中存在 transaction_id 笔交易 table(如 order_id)。因此,如果 transaction_id 出现在 branch_order_relation 中,我们不应该 select 它。否则我们需要select它。任何人都可以将其整合到上面的 SQL 查询中。我也尝试 google 但无法提出解决方案

transactionsbranch_order_relation 上使用左外连接并添加 where 子句 branch_order_relation.order_id is null.

这将选择不在 branch_order_relation 中的交易,见下文

select transaction_id,source_id,destination_id 
from transactions 
left outer join branch_order_relation on transactions.transaction_id = branch_order_relation.order_id
 where branch_order_relation.order_id is null

然后加入其他表,加上你的where子句

我将查询修改为

private static final String SELECT_ORDERS_BY_BRANCH = "select transaction_id,source_id,destination_id from transactions,branch_pincode_relation,branch_details where branch_details.branch_email = ? and branch_details.branch_id = branch_pincode_relation.branch_id and branch_pincode_relation.origin_pincode = transactions.start_pin and transactions.parent_transaction_id IS NOT NULL and transactions.order_status = "+JiffieConstants.PAYMENT_SUCCESS+" and NOT EXISTS (select null from branch_order_relation where branch_order_relation.order_id = transactions.transaction_id)";

及其工作原理。谢谢!