将两个查询合并为一个

时间:2012-02-10 11:08:27

标签: mysql sql join

有没有办法将这两个查询合并为一个?

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的想法

5 个答案:

答案 0 :(得分: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 对结果进行排序

被修改

已提出非联合解决方案的请求。我没有。

答案 1 :(得分:3)

对于Oracle

从TABLE中选择NVL(foo,bar),其中foo喜欢'%foo%'或bar喜欢'%foo%';

答案 2 :(得分:2)

如果您不希望在bar返回记录的位置返回foo,请尝试:

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%'))

答案 3 :(得分: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%'

答案 4 :(得分: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%