Why isn't MySQL using an index for this subquery?
I used this:
SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
Which would give me an array of layerIDs, and then I would loop and do this for each one:
SELECT DATA
FROM drawings
WHERE layerID = ?
And everything worked out great. So now I am trying to do it in one step, so I am trying this:
SELECT DATA , layerID
FROM drawings
WHERE layerID = ANY (
SELECT layerID
FROM layers
WHERE ownerID = ?
AND collectionID = ?
)
But for some reason it doesn't use the index for the main query SELECT DATA etc
! Thus, this merged request takes much longer than completion compared to the separate requests I have done before. (By the way, the subquery SELECT layerID etc
still uses the index).
I have determined whether it is using a query or not using the EXPLAIN statement.
I have separate indexes on columns ownerID
and collectionID
table layers
and column layerID
in the table drawings
.
What am I doing wrong with my request?
source to share
I have never seen the ANY keyword before, but if you try
SELECT DATA, layerID FROM drawings WHERE layerID IN ( SELECT layerID FROM layers WHERE ownerID =? AND collectionID =? )
will it be the same problem? I believe that this should not be the case. However, INNER JOIN is probably slightly better.
source to share