mysql分页与左连接和LIKE - >超级慢

时间:2013-11-08 21:34:42

标签: mysql sql left-join

所以 - 我有两张桌子:

entries表:

id - Primary key
meta_keys VARCHAR 20
meta_desc VARCHAR 20
..some other unimportant columns...

headwords表:

id -  Primary key
fk_entries_id - foreign key refers to entries(id)
headword_text VARCHAR(200)
..some other unimportant columns...

因此条目可能有多个词条 - 对。所以我只是试图在他们的词条中包含某些单词的条目进行分页。我提出的唯一查询需要LEFT JOIN然后LIKE并且有点慢。

SELECT entries.*, GROUP_CONCAT(DISTINCT headwords.headword_text SEPARATOR ' ') AS hw 
FROM entries 
LEFT JOIN headwords ON (entries.id = headwords.fk_entries_id) 
GROUP BY entries.id
HAVING hw LIKE '%dog%' 
LIMIT 20,20;

寻求建议以加快这种方法。

编辑>等待 - 这是一个错误的查询吗?:

SELECT entries.id, GROUP_CONCAT(DISTINCT headwords.headword_text SEPARATOR ' ') AS hw 
FROM entries 
LEFT JOIN headwords 
ON (entries.id = headwords.fk_entries_id) 
WHERE headwords.headword_text LIKE 'dog%' 
GROUP BY entries.id;

1 个答案:

答案 0 :(得分:0)

您应该使用IN比较来避免所有字符串连接和搜索:

select e.*
from entries e
where e.id IN (
   select distinct fk_entries_id
   from headwords
   where headword_text like '%dog%'
)
order by e.id
limit 20,20;

此外,如果您只是通过将'%dog%'替换为'dog%'来匹配单词的START,则可以进一步提高它的性能。这将进一步提高性能,因为您不再需要考虑每个标题词前面添加的文本。