Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two queries into one

Tags:

sql

join

mysql

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

like image 787
Duglas Avatar asked Feb 10 '12 11:02

Duglas


People also ask

How do I join two or more queries in SQL?

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 ).

How do I combine two SQL queries in one result without a UNION?

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.

How do I merge two MySQL queries?

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.


2 Answers

Edited

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.

Edited

A request has been made for a non-union solution. I don't have one.

like image 138
Bohemian Avatar answered Oct 19 '22 22:10

Bohemian


For Oracle

Select NVL(foo,bar) from TABLE where foo like '%foo%' or bar like '%foo%';

like image 45
Kamal Avatar answered Oct 19 '22 22:10

Kamal