Reputation: 251
Is there a way to join this two queries into one?
query = "select foo from TABLE where foo like '%foo%'";
if (query.empty())
query = "select bar from TABLE where bar like '%foo%'"
Update:
select ifnull(foo,bar) from TABLE where foo like 'foo%' or bar like '%foo%';
Thanks to Kamal for the idea
Upvotes: 6
Views: 255
Reputation: 36126
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%'
Upvotes: 2
Reputation: 424973
I just realised that this can return multiple rows - here's the fix:
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%')
Using UNION ALL
(not UNION
) will be faster, because UNION
sorts the results.
A request has been made for a non-union solution. I don't have one.
Upvotes: 5
Reputation: 5522
For Oracle
Select NVL(foo,bar) from TABLE where foo like '%foo%' or bar like '%foo%';
Upvotes: 3
Reputation:
If you don't want bar
returned where foo
does return record(s), try:
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%')
Alternatively, a version without a union:
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%'))
Upvotes: 2
Reputation: 8871
I do not know mysql syntax but in sql server we use like this :-
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%
Upvotes: 1