how to find number of records in both table using join.
i have two tables table1 and table2 with same structure.
table1
id | item |
---|---|
1 | A |
1 | B |
1 | C |
2 | A |
2 | B |
table2
id | item |
---|---|
1 | A |
1 | B |
2 | A |
2 | B |
2 | C |
2 | D |
Output should be like this.
id | table1.itemcount | table2.itemcount |
---|---|---|
1 | 3 | 2 |
2 | 2 | 4 |
2
Answers
Assuming that each
id
is guaranteed to exist in both tables, the following would workBut if that is not guaranteed then we’ll have to use full outer join to get unique ids from both tables
We’re using
coalesce
here as well forid
because if it only exists in t2,t1.id
would result in null.@DeeStark’s answer also works if ids are guaranteed to be in both tables but it’s quite inefficient because count is essentially run twice for every distinct id in the table. Here’s the fiddle where you can test out different approaches. I’ve prefixed each query with explain which shows the cost
Hope this helps