如何使用Join在MySql中应用索引

时间:2016-03-01 12:29:07

标签: mysql indexing

我对索引不是很熟悉。我正在对记录应用索引,因为它花了很多时间在表上查找结果。查询工作正常

SELECT words.wordid, synsets.synsetid, pos, definition
FROM words, senses, synsets
WHERE words.wordid = senses.wordid
AND senses.synsetid = synsets.synsetid
AND lemma='apple'


| wordid | lemma               |                       
+--------+--------------------+-
|  1     | Apply               |
|  2     | PRIMARY             |
|  3     | DEPENDENT           |
+----+--------------------+-----

其他表格

wordid  casedwordid  synsetid  senseid  sensenum    laxid   tagcount
1         19        108659519   1       1       0   0
2       1-hitter    108970180   2       1       0   0
3        NULL       104510146   5       1       0   0 

Synset的第3表

感官表

synsetid   pos     lexdomainid  definition
108659519   n       3   that which is perceived or known or inferred to have its
108970180   n       3   an entity that has physical existance   
104510146   n       3   a general concept formed by extracting common features   

sql查询工作正常,但现在我必须应用索引来获得比简单查询更快的结果。

如何在这三个表上应用索引

2 个答案:

答案 0 :(得分:0)

如果你只运行SELECT,那么

SELECT words.wordid, synsets.synsetid, pos, definition
    FROM words, senses, synsets
    WHERE words.wordid = senses.wordid
    AND senses.synsetid = synsets.synsetid
    AND lemma='apple'

您需要这些索引(请参阅手册中的更多内容:http://dev.mysql.com/doc/refman/5.7/en/create-index.html):

-- create simple b tree indexes for int fields (improve join performance)
CREATE INDEX words_wordid ON words (wordid);
CREATE INDEX senses_wordid ON senses (wordid);
CREATE INDEX senses_synsetid ON senses (synsetid);
CREATE INDEX synsets_synsetid ON synsets (synsetid);

-- we create an index using the first 20 characters of the lemma
CREATE INDEX words_lemma ON synsets (lemma(20));

如果要运行另一个选择查询,则应添加更多索引以提高选择性能:)

答案 1 :(得分:0)

首先,让我们使用JOIN..ON语法:

SELECT  words.wordid, synsets.synsetid, pos, definition
    FROM  words
    JOIN  senses ON words.wordid = senses.wordid
    JOIN  synsets ON senses.synsetid = synsets.synsetid
    WHERE  words.lemma='apple' 

现在,我们可以看到WHERE子句中唯一有用的是words.lemma。所以,让我们来words

INDEX(lemma)

在查看了苹果words后,下一个表格为senses。现在该表需要:

INDEX(wordid)

最后要有效地进入synsets,请

INDEX(synsetid)

根据列名称,我猜测 synsetid已经是PRIMARY KEY。请注意,PRIMARY KEY是一个UNIQUE密钥,INDEX。所以,如果是PK,请不要添加我建议的INDEX

Cookbook on indexing