I have 3 tables: products, categories and pro_cat_link. A product can be linked to one or many categories through the table pro_cat_link.
My query must answer the fo
You could eliminate the performance problems of grouping and counting if you stored that information somewhere. You could add a column to Products called total_categories
that will tell you how many categories the product participates in. Then you could just say where total_categories = 4
. This might be more difficult to maintain if products are often changing their categories because you'd have to constantly update this field correctly - and then you have to decide if you want to do that in application code or in a trigger or in a stored procedure...
Normally I would not think it a very good idea to store such metadata directly in a table, but if the performance is really that bad, it might be worth considering.