In the query I am fetching data from three tables : company
, classes_by_company
, and person
. I have a foreign key in all tables with the name company_id
. I use a left join to mesh the tables with a matching company_id
. I am trying to find out the amount of classes per company and employees. I am getting values that are not correct for both. Here is a SQIDDLE
SELECT a.id,
a.company_id,
a.status,
COUNT(c.company_id) AS classes_per_company,
COUNT(p.employee_id) AS employees_per_company
FROM company a
LEFT JOIN classes_by_company c
ON a.company_id = c.company_id
LEFT JOIN person p
ON a.company_id = p.company_id
GROUP BY a.company_id
Table structure:
CREATE TABLE company
(
id int auto_increment primary key,
company_id int,
status varchar(20)
);
CREATE TABLE classes_by_company
(
id int auto_increment primary key,
company_id int,
class_name varchar(20)
);
CREATE TABLE person
(
id int auto_increment primary key,
employee_id int,
company_id int,
person_name varchar(20)
);