Mysql – thesql query to get the count of each element in a column

MySQLsql

i have a table called category in which i have main category ids and names and each main category has sub category ids and names.i also have a product table with a category id column which either has a numeric sub category id or a 2 letter main category id eg:EL for electronics..my problem is how to get top categories ie., number of products in each category in descending order.

category
{
sub_cat_id - numeric
sub_cat_name - varchar
main_cat_id - varchar (2 characters)
main_cat_name
}
products
{
categoryid,//this can be either main_cat_id or sub_cat_id 
}

pls help….

Best Answer

if there is no namespace clash between main category id and sub category id, you could :

select main_cat_id , count(*) as total
from category
where ( main_cat_id in (select categoryid from products) 
                       OR 
       sub_cat_id in (select categoryid from products)
       )
group by main_cat_id 
order by total desc

however , prima facie there seems to be a problem with the design of the category table. sub_cat should be a different table with appropriate constraints.