【问题标题】:Oracle:Select Statement with If else in OracleOracle:在Oracle中选择带有If else的语句
【发布时间】:2020-10-02 05:36:33
【问题描述】:

我有以下两个表 TestCustomer 和 TestEmail。我想根据 TestCustomer 上的 email_stat 和外部布尔参数“noFlag”检索 emailAddress。如果 noFlag 为“true”,则获取与 customer_id 关联的所有电子邮件地址,其他仅获取“A " 的。任何帮助将不胜感激。

create table TestEmail(emai_id varchar(18),emailaddress varchar(20))

create table TestCustomer(customer_id varchar(18),emai_id varchar(18),email_stat char(1))

Insert Into TestEmail(emai_id,emailaddress)values('12345','abc@gmail.com');
Insert Into TestEmail(emai_id,emailaddress)values('123456','abcd@gmail.com');
Insert Into TestEmail(emai_id,emailaddress)values('123457','abcde@gmail.com');

Insert Into TestCustomer(customer_id,emai_id,email_stat)values('223459','12345','A');
Insert Into TestCustomer(customer_id,emai_id,email_stat)values('223458','123456','I');
Insert Into TestCustomer(customer_id,emai_id,email_stat)values('223459','123457','A');

预期输入:

customer_id=223458 和 noFlag='true'

预期输出

预期输入:

customer_id=223458 和 noFlag='false'

预期输出

空结果。

【问题讨论】:

  • 为什么这个标签是mysql?

标签: sql oracle oracle11g oracle10g


【解决方案1】:
SELECT [DISTINCT] emailaddress 
FROM TestEmail
JOIN TestCustomer USING (emai_id)
-- insert parameter-1 instead of 223458
WHERE TestCustomer.customer_id = 223458                      
-- insert parameter-2 instead of 'noFlag'
  AND TestCustomer.email_stat = CASE WHEN noFlag = 'true' 
                                     THEN TestCustomer.email_stat
                                     ELSE 'A'
                                     END

fiddle

【讨论】:

    【解决方案2】:

    如果您只想要电子邮件,可以使用exists

    select e.emailaddress
    from testemail e
    where exists (select 1
                  from testcustomer c
                  where c.email_id = e.email_id and
                        c.customer_id = :customer_id and
                        (c.email_stat = 'A' or :noflag = 'true')
                 );
    

    【讨论】:

    • 如果我也想要一些来自 TestCustomer 的字段,如何修改它
    • 这不是你在这里问的问题。这回答了您提出的问题。
    猜你喜欢
    • 2013-03-14
    • 2021-08-17
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    相关资源
    最近更新 更多