Mysql从2个表中计算相同的值作为2个不同的计数

时间:2015-11-20 01:48:06

标签: mysql

我想计算一个存在于2个不同表中的值。但它应该像这样分开显示:

enter image description here

当然,我可以单独计算它。但是我希望在一个结果中的一个查询中使用它。谢谢你的帮助

SELECT `X1`, COUNT(`X1`) AS Sales FROM `table1` GROUP BY `X1`

SELECT `X1`, COUNT(`X1`) AS Purchases FROM `table2` GROUP BY `X1`

2 个答案:

答案 0 :(得分:1)

这很痛苦,因为每个表中的x1值集可能不一样。

以下是使用union allgroup by的一种方法:

select x1, sum(sales) as sales, sum(purchases) as purchases
from ((select x1, count(*) as sales, 0 as purchases
       from table1
       group by x1
      ) union all
      (select x2, 0, count(*)
       from table2
       group by x1
      )
     ) t12
group by x1;

答案 1 :(得分:0)

使用子查询从其中一个表中获取计数,然后将其与另一个表连接。

SELECT t1.x1, COUNT(*) AS sales, t2.purchases
FROM table1 AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
       FROM table2
       GROUP BY x1) AS t2
ON t1.x1 = t2.x1
GROUP BY t1.x1

在两个子查询中进行分组实际上可能更有效。

SELECT t1.x1, t1.sales, t2.purchases
FROM (SELECT x1, COUNT(*) AS sales
      FROM table1
      GROUP BY x1) AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
      FROM table2
      GROUP BY x1) AS t2
ON t1.x1 = t2.x1

但是,如果两个表中都没有x1个值,则这两个查询都会将它们排除在外。理想的解决方案是FULL OUTER JOIN,但MySQL没有这个操作。有关解决方法,请参阅Full Outer Join in MySQL。 Gordon Linoff的回答并没有出现这个问题。或者,如果您有另一个列出所有x1值的表,则可以将其用作主表,并使用LEFT JOIN上述两个子查询。