To make your correlated subquery work with the same table, you would have to use table aliases:
SELECT category_id
,count(*) AS total_count -- unquoted column alias with space is wrong, too
,(SELECT count(*)
FROM products AS p1
WHERE product_path LIKE '%Electronics%'
AND p1.category_id = p.category_id
) AS electronic_count
FROM products AS p
WHERE product_path LIKE '%Products%'
GROUP BY category_id;
Assuming id
is the primary key and, as such, NOT NULL
. Then count(*)
does a better job.
But this can be further simplified to:
SELECT category_id
,count(*) AS total_count -- keyword AS is needed for column alias
,count(product_path LIKE '%Electronics%' OR NULL) AS electronic_count
FROM products p -- keyword AS is just noise for table alias
WHERE product_path LIKE '%Products%'
GROUP BY category_id;
Much faster.
count()
only counts non-null values. By adding OR NULL
I convert FALSE
to NULL
. Thereby only those rows count, where product_path LIKE '%Electronics%'
evaluates to TRUE
.