I have two tables: Table A and Table B:
Table A
+--------+----------+------------+
| cat_id | cat_name | is_deleted |
+--------+----------+------------+
| 1 | name 1 | 0 |
+--------+----------+------------+
| 2 | name 2 | 0 |
+--------+----------+------------+
| 3 | name 3 | 1 |
+--------+----------+------------+
Table B
+--------------+----------+--------+------------+
| event_cat_id | event_id | cat_id | is_deleted |
+--------------+----------+--------+------------+
| 1 | 13 | 2 | 0 |
+--------------+----------+--------+------------+
| 2 | 23 | 2 | 1 |
+--------------+----------+--------+------------+
| 3 | 3 | 2 | 0 |
+--------------+----------+--------+------------+
I need to retrieve all records from Table A and get the amount of event_id for each cat_id from Table B so that I would have the following result for the above values:
"categories": [
{
"cat_name": "Name 1",
"is_deleted": "0",
"total_items": "0"
},
{
"cat_name": "Name 2",
"is_deleted": "0",
"total_items": "2"
}
]
What I tried so far without success was as follows:
SELECT TABLE_A.cat_name, TABLE_A.is_deleted,
COUNT(TABLE_B.cat_id) AS total_items
FROM TABLE_A LEFT JOIN TABLE_B ON (TABLE_A.cat_id = TABLE_B.cat_id)
WHERE TABLE_A.is_deleted = 0 AND TABLE_B.is_deleted = 0
GROUP BY TABLE_A.cat_name
This query returns wrong values for total_items
. Why?