The table:
id | category (there is a index on id & category)
-----------
1 | 1
1 | 7
1 | 3
2 | 1
2 | 2
2 | 4
3 | 1
3 | 6
3 | 3
SELECT DISTINCT
category
FROM
many_to_many e1
WHERE id IN
(
SELECT DISTINCT
e1.id
FROM
many_to_many e1
INNER JOIN
many_to_many x1
ON e1.id=x1.id
WHERE
e1.category IN (3)
)
I like to get retured: ** 6, 1, 7** (what I do get with the query above)
It seems to me this query is not gone preform well, because the sub query searches all the ID’s and this list can be huge.
Also it doesn’t matter how many but if the ID is related.
So for performance if there would be 100 id’s checking once for each unique category to be populated would be enough.
Secondly I use an other query (the sub query )the get all id’s who contain the category:
SELECT DISTINCT
e1.id
FROM
many_to_many e1
INNER JOIN
many_to_many x1
ON e1.id=x1.id
WHERE
e1.category IN (3)
returns: 3 & 1
What would be the most efficient way to query the result I like. Is there an more efficient (better preforming) solution?
Should I use one instead of two query’s?
You shouldl check the plan of the query with EXPLAIN. A compound index on
(category, id)might be good for this query.