Mysql - 结合2个SQL查询

时间:2016-05-13 09:28:49

标签: mysql sql

我有2个查询返回2个结果集。 如何将这两个查询组合起来得到一个结果?

第一次查询:

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

第二次查询:

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

请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用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" ;

请注意,如果您希望获得两个查询中的重复元素,则可以使用UNION ALL

使用UNION时,请确保查询结果的列数相同。

答案 1 :(得分:0)

试试这个:

SELECT *
FROM Base base
INNER JOIN Child child ON child.base_id = base.id
WHERE ( base.`status` = "active" 
AND base.application = "template" )or (base.`status` = "active" and base.application = "template" and base.role = "public");