This is probably very simple, but for some reason I am pulling a blank on this one..
I want to join two tables and get the total occurrences of a column in one table within another table.
Table1
id | company
------------
1 | companyA
2 | companyB
3 | companyC
Table2
id | company_id
------------
1 | 2
2 | 2
3 | 1
4 | 2
5 | 3
The result should be:
company | count(*)
------------------
companyA| 1
companyB| 3
companyC| 1
I can’t seem to get the count portion correct. I was thinking that it would be something like:
SELECT Table1.company, count(*)
FROM Table1 JOIN Table2 ON
Table1.id = Table2.company_id
GROUP BY Table1.company;
Revised: The problem is actually that companyA and companyB come up correctly, but it’s not showing companyC. I went through and double checked that there are matches in the fields for companyC which there were.
it should be
Table2.company_idthat you are joining with and notTable2.idyou must define an
INDEX(probably UNIQUE) on columncompanyoftablefor faster performance since you are grouping it withcompanyUPDATE 1