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

时间:2018-08-09 08:15:44

标签: sql postgresql

我有下表:

|--------|----------------|-------------|
|  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 个答案:

答案 0 :(得分:2)

您可以在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

一种可能更好的解决方案是使用EXISTSCROSS 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

答案 1 :(得分:0)

请尝试以下查询:

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

答案 2 :(得分:0)

select * from my_table 
where 
((SELECT DISTINCT 1 FROM my_table where for_country='Germany') = 1 AND for_country='Germany')
OR for_country='All'

答案 3 :(得分:0)

我将UNIONNOT 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');

答案 4 :(得分:0)

我会这样写:

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'
      );
相关问题