我有一个这样的表,类型是innodb,id和sid被编入索引。
id | sid
##########
1 | 100
1 | 101
1 | 102
1 | 103
1 | 104
1 | 105
2 | 100
2 | 101
3 | 100
3 | 101
我需要id有sid 100,... 105喜欢id = 1。 我有这个查询
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
但是当我运行查询时,phpmyadmin会挂起。 记录数量为2000。
什么是优化查询?
答案 0 :(得分:1)
令人惊讶的是,显示的SQL语句编译/运行。
但是,您可以通过重写当前最后一行来拯救它:
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;
此查询是否最佳?
鉴于您对Maulik Vora的答案的评论,范围{100 .. 105}只是一个例子,那么我们需要知道它是否总是6个值,或者它是5还是7或其他数字。但是,最佳结构可能使用临时表(称为ListToMatch,其中包含非空唯一列SID),其中包含所需的任何值,并且查询为:
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);
将您感兴趣的值集插入ListToMatch;然后,您可以获取匹配的ID值列表。这可能更接近最优,尤其是因为它可以像对6那样轻松地适应1值和100值,而用100路自连接重写SQL并没有太多考虑。
答案 1 :(得分:0)
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