I have a table like this and type is innodb and id and sid are indexed.
id | sid
##########
1 | 100
1 | 101
1 | 102
1 | 103
1 | 104
1 | 105
2 | 100
2 | 101
3 | 100
3 | 101
I need id’s have sid 100,…105 like id=1.
I have this query
select t1.id
from test as t1, test as t2, test as t3,
test as t4, test as t5, test as t6
where t1.sid=100
and t2.sid=101
and t3.sid=102
and t4.sid=103
and t5.sid=104
and t6.sid=105
and t1.id = t2.id = t3.id = t4.id = t5.id = t6.id
but phpmyadmin hangs when I run query.
The number of records is 2000.
What is optimized query?
It is surprising that the SQL statement shown compiles/runs.
However, you can probably rescue it by rewriting what is currently the last line to:
Given your comment to Maulik Vora’s answer that the range { 100 .. 105 } is just an example, then we need to know whether it is always 6 values or whether it could be 5 or 7 or some other number. However, it is likely that the optimal structure uses a temporary table (call it ListToMatch with a non-null unique column SID) containing whatever values are needed, and that the query is:
You insert the set of values you’re interested in to ListToMatch; you can then get the list of ID values that match. This is likely to be more nearly optimal, not least because it adapts to 1 value and 100 values as easily as it does to 6, whereas rewriting the SQL with a 100-way self-join doesn’t bear much thinking about.