2011-10-03 60 views
0

我有一個這樣的表,類型是innodb,id和sid是索引的。在查詢中使用'as'

id | sid 
    ########## 
    1 | 100 
    1 | 101 
    1 | 102 
    1 | 103 
    1 | 104 
    1 | 105 
    2 | 100 
    2 | 101 
    3 | 100 
    3 | 101 

我需要id's sid 100,... 105 like 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

顯然,他希望挑出ID與{100 .. 105}中每個sid值相關聯的所有ID值。如果其中一個sid值丟失,請忽略該ID。 –

回答

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沃拉的回答您的評論的範圍{100 ... 105}僅僅是一個例子,那麼我們需要知道它是否總是6個值或是否可能是5或7或其他一些數。但是,它可能是最佳的結構使用臨時表包含任何需要的值(與非空的唯一列SID稱之爲ListToMatch),和查詢是:

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值列表。這很可能是更接近最優的,不僅僅是因爲它適應1值和100值的容易度與6倍一樣容易,而用100方式自連接重寫SQL並沒有太多考慮。

+0

我的答案是什麼? –

+0

這個查詢是否最優? – user677900

+0

可能不會 - 但工作比非工作要好。我不完全確定原稿爲什麼會掛起,但它很可能與最後一行的解釋方式有關。 –

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 
+0

我正在檢查你的答案。謝謝你 – user677900

+0

範圍{100,105}就是例子。值是動態的。它可以是100,200,201,.. – user677900

+1

我最初說'+1的替代方法,但爲什麼不:'SELECT ID FROM測試GROUP BY ID HAVING COUNT(ID)= 6 AND MIN(ID)= 100 AND MAX(id) = 105'?'然後我意識到:假設表中id = 1的表中有sid = 99(或106)的條目。這應該仍然允許查詢選擇id = 1。因此,修改後的查詢需要:SELECT id FROM test WHERE id BETWEEN 100 AND 105 GROUP BY id HAVING COUNT(id)= 6 AND MIN(id)= 100 AND MAX(id)= 105'。當然,6對應於'105 - 100 + 1'。 –