如何组合这些SQL查询以获得一个结果?

时间:2015-03-07 21:54:44

标签: mysql sql

使用MySQL,我有多个数据库表,它们包含相同的结构/列名,但数据不同。我可以使用以下查询从表1 获取所有相关数据:

SELECT heading, COUNT( * ) AS number FROM TABLE1
WHERE category = 'PARENT'
GROUP BY heading ORDER BY number DESC

我可以使用表2 获取所有相关数据:

SELECT heading, COUNT( * ) AS number FROM TABLE2
WHERE category = 'PARENT'
GROUP BY heading ORDER BY number DESC

这继续使用TABLE3,TABLE4等

如何组合查询以便我有1个查询和一个结果?而不是每个表的单独结果?

我已尝试在查询之间放置UNION,但它没有给我我想要的结果......

2 个答案:

答案 0 :(得分:1)

“全部联盟”您的查询,但将整个查询放在子选择中。然后这样做:

Select heading
,            sum(number)
from ( [your queries with union all] )
group by heading

答案 1 :(得分:1)

您可以在结果中选择UNIONGROUP以及ORDER

SELECT heading, COUNT(*) AS number
  FROM (SELECT heading FROM TABLE1
         WHERE category = 'PARENT'
         UNION -- or UNION ALL - see comment below
        SELECT heading FROM TABLE2
         WHERE category = 'PARENT')
 GROUP BY heading ORDER BY number DESC;

p.s。 此假设您希望对除TABLE2TABLE1之外的所有行进行计数和分组。如果您还要计算双联,请在上面的代码段中使用UNION ALL

另外 (根据上面添加的评论):

SELECT heading, SUM(number) AS number
  FROM (SELECT heading, COUNT(*) AS number FROM TABLE1
         WHERE category = 'PARENT'
         UNION -- or UNION ALL - see comment below
        SELECT heading, COUNT(*) AS number FROM TABLE2
         WHERE category = 'PARENT')
 GROUP BY heading ORDER BY number DESC;