2013-12-20 52 views
0

我有一個像如何讓這種緩慢的查詢速度更快

table1的表:

word id 
a 1 
a 2 
a 10 
c 1 
d 2 
e 30 
f 10 

現在,如果字= 'a'然後我需要找出'c'和`「d」和「F」。 我寫了一個查詢,它的工作但花費了太多時間,因爲表包含大量數據。

查詢:

SELECT DISTINCT word 
FROM table1 
WHERE id IN (SELECT id 
      FROM table1 
      WHERE word = 'a') 
+3

索引可能? – opalenzuela

+1

sqlfiddle爲大家的方便:http://www.sqlfiddle.com/#!2/d845c/1 – mtanti

回答

1
SELECT DISTINCT(t1.word) 
FROM table1 t1 
INNER JOIN table1 t2 ON (t1.id = t2.id AND t2.word = 'a') 

這應該是更快,因爲它沒有做一個子查詢。

此外,添加索引(即單詞)將有助於加快查詢速度。

1

你可以使用一個自聯接:

SELECT DISTINCT t1.word 
FROM table1 t1 
JOIN table1 t2 on t1.id = t2.id 
WHERE t2.word = 'a' 

但你當然需要相應的索引。

0

嘗試......

SELECT t.word 
FROM table1 t 
     INNER JOIN Table1 tt ON t.id = tt.id AND t.word <> 'a' 
WHERE tt.word = 'a' 

否則,另一種方式是....

SELECT t.word 
FROM table1 t 
     INNER JOIN Table1 tt ON t.id = tt.id 
WHERE tt.word = 'a' AND t.word <> 'a' 
0

通常EXISTS優於IN關於性能。所以,請嘗試這一個,以及:

SELECT DISTINCT word 
FROM table1 t1 
WHERE EXISTS(SELECT * 
      FROM table1 t2 
      WHERE t2.word = 'a' and t2.id = t1.a) 

但是,請注意,有很多次,有必要採用其他技術來提高查詢的性能。正如其他人所說,創建索引是一種選擇。

0

嘗試:

SELECT DISTINCT t1.word FROM table1 AS t1 
INNER JOIN table1 AS t2 ON t1.id = t2.id 
WHERE t2.word = 'a' 
相關問題