将两个查询合并为一个。

6
有没有一种方法将这两个查询合并成一个?
query = "select foo from TABLE where foo like '%foo%'";

if (query.empty())
    query = "select bar from TABLE where bar like '%foo%'"

更新:

select ifnull(foo,bar) from TABLE where foo like 'foo%' or bar like '%foo%';

感谢Kamal提供的想法


如果你说“query.empty()”,是指查询的结果吗? - Diego
5个回答

5

编辑

我刚意识到这可以返回多行 - 这里是修复方法:

select foo from TABLE where foo like '%foo%'
union all
select bar from TABLE where bar like '%foo%'
and not exists (select 'x' from TABLE where foo like '%foo%')

使用UNION ALL(而不是UNION)会更快,因为UNION会对结果进行排序

编辑后

要求提供非联合解决方案,但我没有找到。


查询中为什么有一个 X - Starx
@Bohemian,谢谢你的回答,但是请问有没有不用 union 的方法? - Duglas
我可能理解有误,但据我所知,他只想要第二个查询,如果第一个查询为空,所以没有必要像你所做的那样运行3个查询。 - Diego
@Duglas 感谢您注意到这个笔误 - 已经修复了。 - Bohemian
@Diego 我看不到任何绕过这3个查询的方法。 - Bohemian
嘿 @Bohemian!看一下我的答案。我不明白为什么要使用联合,这里没有需要联合的东西。如果第一个查询返回结果,他只想要第一个,如果没有,他想要第二个。一个简单的if语句就能解决问题。 - Diego

3

针对Oracle

从TABLE表中选择NVL(foo,bar),其中foo或bar包含'%foo%'字符串;


2
如果您不希望在foo返回记录时也返回bar,请尝试以下方法:
select foo from TABLE where foo like '%foo%'
union all
select bar from TABLE
where bar like '%foo%' and 
      not exists (select null from TABLE where foo like '%foo%')

或者,没有联合的版本:

select case when foo like '%foo%' then foo else bar end as foobar
where foo like '%foo%' or 
      (bar like '%foo%' and 
       not exists (select null from TABLE where foo like '%foo%'))

但是,就像@Bohemian所说的那样,使用union all将会删除重复项,这可能不是想要的结果,对吧? - aF.
@aF。union all不会删除重复项,而union则会。 - Bohemian

2
   if not exists (select top 1 foo from TABLE where foo like '%foo%')
        select bar as MyColumn from TABLE where bar like '%foo%'
    else
        select foo as MyColumn from TABLE where foo like '%foo%'

1

我不懂mysql语法,但在sql server中我们是这样使用的:

  IF EXISTS(select foo from TABLE where foo like '%foo%')
    BEGIN 
    select foo from TABLE where foo like '%foo%'
    END
    ELSE
    select bar from TABLE where bar like '%foo%

他想将两个查询合并为一个,不纠正语法 :P - aF.
1
不要,他只想要第二个if语句,如果第一个没有返回任何东西。 - Diego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接