What I have is a table that has different fields and among them the fields that are called category1, category2. Let’s say there is some data stored there
(cat1, cat2), (cat2, cat1), (cat3, cat1), (cat3, cat4), (cat1, cat2), (cat2, cat3)
A row can’t have duplicate categories, i.e. (cat1, cat1) is not possible. Is there an easy way to get an output like this
(cat1, 4), (cat2, 4), (cat3, 3), (cat4, 1)
What I currently do is
(SELECT category1 AS category UNION ALL SELECT category2 AS category) AS tmp
and then I deal with this tmp table and group by it. The problem is that I can’t find a way to optimize it. So the question is: can you think of any better way to do the select above which would allow me to use indexes? If not, is the only way to do this – to actually create this tmp table and index it?
1 Answer