Hello.
I have two tables, foo
and bar
:
+----+-----+ +----+-----+
| id | val | | id | val |
+----+-----+ +----+-----+
| 1 | qwe | | 1 | asd |
| 2 | rty | | 3 | fgh |
+----+-----+ +----+-----+
id
is not unique here. Not all IDs in foo
have their equivalents in bar
and vice versa. I need to count all rows with specific ID in both tables and present them in a new table, e.g.:
+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 3 | 0 | 1 |
+----+-----------+-----------+
I've tried UNION SELECT
:
SELECT id, COUNT(id) AS count_foo, 0 AS count_bar FROM foo GROUP BY id
UNION SELECT id, 0, COUNT(id) FROM bar GROUP BY id;
But this outputs row with id=1
twice, like
+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
| 1 | 1 | 0 | <- not good
| 2 | 1 | 0 |
| 1 | 0 | 1 | <- not good
| 3 | 0 | 1 |
+----+-----------+-----------+
I've also tried LEFT JOIN
:
SELECT id, COUNT(foo.id) AS count_foo, COUNT(bar.id) AS count_bar
FROM foo LEFT JOIN bar USING(id) GROUP BY id;
But this query ignores rows from table bar
with ID that is missing in table foo
:
+----+-----------+-----------+
| id | count_foo | count_bar |
+----+-----------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 0 |
+----+-----------+-----------+ <- can I haz `id=3`?
What am I missing? What would be the right query or the right manual to read?
Thanks.