代码之家  ›  专栏  ›  技术社区  ›  Saurabh Palatkar

PostgreSQL中不带if-else语句的条件选择

  •  0
  • Saurabh Palatkar  · 技术社区  · 7 年前

    我有下表:

    |--------|----------------|-------------|
    |  url   |   description  |  for_region |
    |--------|----------------|------------ |
    | url1   |   desc1        |  All        |
    | url2   |   desc2        |  All        |
    | url2   |   desc3        | Germany     |
    |--------|----------------|-------------|
    

    现在,我试图在不使用if else语句的情况下编写以下查询:

    IF EXISTS (SELECT 1 FROM my_table where for_country='Germany') THEN
       select * from my_table where for_country='Germany'
    ELSE 
       select * from my_table where for_country='All'
    END IF;
    

    不使用if-else语句重写上述查询的最佳方法是什么?

    5 回复  |  直到 7 年前
        1
  •  2
  •   Radim Bača    7 年前

    您可以添加 EXISTS 进入 WHERE 条款

    select * 
    from my_table 
    where (EXISTS (select 1 from my_table where for_country='Germany') and for_country='Germany') OR
          (NOT EXISTS (select 1 from my_table where for_country='Germany') and for_country='All')
    

    DBFiddle DEMO

    一个可能更好的解决方案是 存在 CROSS JOIN 避免同一子查询的重复调用

    select my_table.* 
    from my_table 
    cross join (
      select exists(select 1 from my_table where for_country='Germany') exst
    ) t
    where (t.exst and for_country='Germany') OR
          (not t.exst and for_country='All')
    

    DBFiddle DEMO

        2
  •  0
  •   Fahmi    7 年前

    尝试以下查询:

    select m1.name from
       (
        select m1.*, case when m1.for_region='Germany' then 1  else 0  end  as cnt from tableA m1 ) m1
         inner join 
        (
        select max(Cnt) as Cnt from
        (
         select t1.*, case when for_region='Germany' then 1  else 0  end  as Cnt 
          from tableA t1
         ) as t2
    
         )as n 
         on m1.cnt=n.Cnt
    
        3
  •  0
  •   Piotr Rogowski    7 年前
    select * from my_table 
    where 
    ((SELECT DISTINCT 1 FROM my_table where for_country='Germany') = 1 AND for_country='Germany')
    OR for_country='All'
    
        4
  •  0
  •   Yogesh Sharma    7 年前

    我会用 UNION 具有 NOT EXISTS :

    SELECT * 
    FROM my_table 
    WHERE for_country = 'Germany'
    UNION ALL
    SELECT *
    FROM my_table
    WHERE for_country = 'All' AND
          NOT EXISTS (SELECT 1 FROM my_table WHERE for_country = 'Germany');
    
        5
  •  0
  •   Gordon Linoff    7 年前

    我会这样写:

    select t.*
    from my_table t.
    where (for_country = 'Germany') or
          (not exists (select 1 from my_table where for_country = 'Germany') and
           for_country = 'All'
          );