简体   繁体   English

在SQL中使用不存在和子查询

[英]using not exists and subquery in SQL

I have to write an sql query in oracle 11g for the following scenario. 对于以下情况,我必须在oracle 11g中编写一个SQL查询。

I have a table customers. 我有桌子的顾客。 It has three columns customer_id,cust_cat and cust_deterioration_date. 它具有三列customer_id,cust_cat和cust_deterioration_date。 customer_id is the primary key. customer_id是主键。

customers
(customer_id varchar2(20),
 cust_cat varchar2(1),
 cust_deterioration_date date
);

I have another table Accounts. 我有另一个表帐户。 It has 4 columns loan_account_number,product_code,account_deterioration_date,customer_id. 它有4列借贷编号,产品代码,帐龄恶化日期,客户编号。 loan_account_number is the primary key. loan_account_number是主键。

Accounts
(loan_account_number varchar2(20),
 product_code varchar2(4),
 account_deterioration_date date,
 customer_id  varchar2(20)
 )

I have to select the customers who has loan accounts having product code as 9213 or 9450 in the accounts table and whose cust_cat is 'G'. 我必须选择在帐户表中具有产品代码为9213或9450的贷款帐户且cust_cat为'G'的客户。

If such a customer has multiple loan accounts with product code 9213 or 9450,and Only if the account_deterioration_date for all those loan accounts are null,I should update cust_deterioration_date in customers table as null. 如果这样的客户有多个产品代码为9213或9450的贷款帐户,并且仅当所有这些贷款帐户的account_deterioration_date为空时,我才应将客户表中的cust_deterioration_date更新为空。

Here is my query to select the reuired customers. 这是我的查询,以选择需要的客户。

SELECT UNIQUE s1.customer_no
FROM   accounts  a1
      ,customers s1
WHERE  a1.customer_id = s1.customer_no
AND    NVL(s1.cust_cat,
           'G') = 'G'
AND    a1.product_code IN ('9213',
                           '9450')
AND    a1.account_deterioration_date IS NULL
AND    NOT EXISTS (SELECT 1
        FROM   accounts a
        WHERE  a.customer_id = s1.customer_no
        AND    a.account_deterioration_date IS NOT NULL
        AND    a.product_code IN ('9213',
                                  '9450'))

This query is fetching the required result but at the cost of performance. 该查询获取所需的结果,但以性能为代价。 Is there any better way to achieve this functionality? 有没有更好的方法来实现此功能?

Thanks in advance 提前致谢

You can aggregate your 9213/9450 account records per customer and see whether there are multiple entries ( count(*) > 1 ) and no non-null account_deterioration_dates ( count(account_deterioration_date) = 0 ). 您可以汇总每个客户的9213/9450帐户记录,并查看是否有多个条目( count(*) > 1 )和没有非空的account_deterioration_dates( count(account_deterioration_date) = 0 )。 With the customer IDs thus found, you can access the customers table. 有了找到的客户ID,您就可以访问客户表。

update customers
set cust_deterioration_date = null
where nvl(cust_cat,'G') = 'G'
and customer_id in
(
  select customer_id
  from accounts
  where product_code in ('9213', '9450')
  group by customer_id
  having count(*) > 1
  and count(account_deterioration_date) = 0
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM