【问题标题】:select 2 recors in case 2 exists在情况 2 存在时选择 2 条记录
【发布时间】:2021-12-01 16:04:36
【问题描述】:

我有 2 行

code name
1   cake
2   chocolate

这个查询给了我两个结果

select * from table a  where a.code=2 or a.code =1

如果其中一条记录未显示,我不想检索任何内容。

select * from table a  where a.code=2 or a.code =1
and exists ( select 1 from table b where a.code=b.code )

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您可以使用解析函数:

    SELECT code,
           name
    FROM   (
      SELECT a.*,
             COUNT(DISTINCT code) OVER () AS num_codes
      FROM   table_name a
      WHERE  a.code IN (1,2)
    )
    WHERE  num_codes = 2;
    

    其中,对于样本数据:

    CREATE TABLE table_name (code, name) AS
    SELECT 1, 'cake'      FROM DUAL UNION ALL
    SELECT 2, 'chocolate' FROM DUAL;
    

    输出:

    CODE NAME
    1 cake
    2 chocolate

    如果你:

    DELETE FROM table_name WHERE code = 1;
    

    然后再次运行查询,它会输出:

    CODE NAME

    db小提琴here

    【讨论】:

      【解决方案2】:

      简单检查count distict

      select * from tab1
      where code in (1,2) 
      and (select count(distinct code) from tab1 where code in (1,2)) = 2;
      

      如果您想丢弃表中有重复行的情况,例如1,1,2

      添加其他谓词过滤器

       and (select count(*) from tab1 where code in (1,2)) = 2
      

      【讨论】:

      • 我正在检查这个
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多