开发者

use 'as' in query

I have a table like this and type is innodb and id and sid are indexed.

  id | sid
  ##########
   1 | 100
   1 | 101
   1开发者_如何学Python | 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:

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
   and t1.id = t3.id
   and t1.id = t4.id
   and t1.id = t5.id
   and t1.id = t6.id;

Is this query optimal?

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:

SELECT T.ID
  FROM Test AS T JOIN ListToMatch AS L ON T.SID = L.SID
 GROUP BY T.ID
 HAVING COUNT(*) = (SELECT COUNT(*) FROM ListToMatch);

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.


select t2.id from (select id, max(sid) as mxsid, min(sid) as mnsid from test
group by id having count(id) = 6) as t2 
where t2.mxsid = 105 and t2.mnsid = 100
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜