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
Use the UNION ALL clause to join data from columns in two or more tables. In our example, we join data from the employee and customer tables. On the left of the UNION ALL keyword, put the first SELECT statement to get data from the first table (in our example, the table employee ).
You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.
The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.
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.
For Oracle
Select NVL(foo,bar) from TABLE where foo like '%foo%' or bar like '%foo%';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With