I have two select statements that take values from two different tables.
the select statements look something like this
SELECT year(timestamp) y, month(timestamp) m, count(id) c
FROM table
WHERE clause="foo"
GROUP BY year(timestamp), month(timestamp)
which returns something like
|-y--|-m|c|
|2013|01|9|
|2013|02|9|
|2013|03|9|
|2013|04|9|
.
SELECT year(timestamp) y, month(timestamp) m, count(id) c
FROM table2
WHERE clause="foo"
GROUP BY year(timestamp), month(timestamp)
which returns something like
|-y--|-m|c|
|2013|01|1|
|2013|03|1|
|2013|04|1|
What I’m looking for is joining the two tables based on the timestamp, and subtract the second table from the first. So it should look like:
|-y--|-m|c|
|2013|01|8|
|2013|02|9|
|2013|03|8|
|2013|04|8|
thanks!
Assuming TableA has your master records, then something like this should work:
I’ve updated the answer. The first part of the union returns all records in table with or without those matching in table2, subtracting the table2 count when available. The second part of the union returns all records in table2 that do not exist in table multiplying the count column by -1.
There may be a simpler approach, but without really understanding the tables, this is the best I can offer. And unfortunately MySQL doesn’t support FULL OUTER JOINs which would alleviate the need for the UNION.