Mysql 将两个查询合并为一个查询
有没有办法将这两个查询合并为一个查询Mysql 将两个查询合并为一个查询,mysql,sql,join,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%'; 感谢您的创意编辑 我刚刚意
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%';
感谢您的创意编辑
我刚刚意识到,这可能会返回多行-修复方法如下:
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
会对结果进行排序
编辑
已请求非工会解决方案。我没有。我不知道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%
如果您不想在
foo
返回记录的位置返回bar
,请尝试:
或者,不带接头的版本:
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%'))
甲骨文
从表中选择NVL(foo,bar),其中foo-like“%foo%”或bar-like“%foo%” if(query.empty())是指查询的结果吗?为什么查询中有一个
X
?@Bohemian,thx为一个,但是tell没有union
?我可能解释错了,但据我所知,如果第一个查询为空,他只想要第二个查询,因此,没有必要像您那样运行3个选择。@Duglas Thx注意到输入错误-修复了它。@Diego我看不出有任何方法可以绕过这3个查询。他想将两个查询合并在一个查询中。不更正语法:Pno,如果第一个没有返回任何+1作为正确的解决方案,他只需要第二个。但是,像@Bohemian一样,使用union all
将删除重复项,而这可能不是所需要的,对吗?@aF.union all
不会删除重复项<代码>联合执行。
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%'))
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%'