Use a subquery to get the counts from one of the tables, and then join that with the other table.
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
It might actually be more efficient to do the grouping in two subqueries.
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
However, if there are any x1
values that aren't in both tables, both these queries will leave them out. The ideal solution is FULL OUTER JOIN
, but MySQL doesn't have this operation. See Full Outer Join in MySQL for a workaround. Gordon Linoff's answer doesn't have this problem. Or if you have another table that lists all the x1
values, you could use that as the main table, and LEFT JOIN
both of the above subqueries with it.