litlitDM litlitDM - 6 months ago 13
SQL Question

Mysql - Combine 2 SQL queries

I have 2 queries which return 2 result sets.
How can i combine these 2 queries to get one single result?

First Query:

SELECT *
FROM Base base
INNER JOIN Child child ON child.base_id = base.id
where base.`status` = "active" and base.application = "template";


Second Query:

SELECT *
FROM Base base
WHERE base.`status` = "active" and base.application = "template" and base.role = "public" ;


Please help.

Answer

You can try to use UNION:

SELECT col1, col2, col3, col4....
FROM Base base
INNER JOIN Child child ON child.base_id = base.id
where base.`status` = "active" and base.application = "template"

UNION

SELECT col1, col2, col3, col4....
FROM Base base
WHERE base.`status` = "active" and base.application = "template" and base.role = "public" ;

Note that if you want to have the duplicate elements from the two queries then you can use UNION ALL.

Also make sure that the number of columns should be same for both the query result when using UNION.