我有下表:
|--------|----------------|-------------|
| 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语句重写上面的查询的最佳方法是什么?
答案 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')
一种可能更好的解决方案是使用EXISTS
和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')
答案 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)
我将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');
答案 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'
);