gpt4 book ai didi

mysql - 提高 MySQL LIKE 查询的速度?

转载 作者:可可西里 更新时间:2023-11-01 07:01:36 24 4
gpt4 key购买 nike

对于具有自动完成功能的机场输入字段,目前有一个机场描述表,autocomplete_airport:

lang | description (with INDEX)                           | ...
-----+----------------------------------------------------+----
pt | New York - John F Kennedy (JFK), Estados Unidos | ...
pt | Nova Iorque - John F Kennedy (JFK), Estados Unidos | ...
...

自动完成适用于单个单词。因此,当用户输入“yor”时,就会显示“new york”(如果在 LIMIT 中)。查询当前的工作方式如下:

SELECT * FROM autocomplete_airport WHERE lang = "pt"
AND (description LIKE "%(yor)%"
OR description LIKE "yor%"
OR description LIKE "% yor%")
ORDER BY description
LIMIT 15

现在我想知道如何加快速度。一种想法是创建以下数据库结构,其中包含表 autocomplete_airportautocomplete_airport_word:

id   | lang | description (with INDEX)                           | ...
-----+------+----------------------------------------------------+----
123 | pt | New York - John F Kennedy (JFK), Estados Unidos | ...
124 | pt | Nova Iorque - John F Kennedy (JFK), Estados Unidos | ...
...

word (with INDEX) | autocomplete_airport_id
------------------+------------------------
New | 123
York | 123
John | 123
F | 123
Kennedy | 123
JFK | 123
...

然后 SELECT 只需要在字符串的开头搜索:

SELECT DISTINCT autocomplete_airport.*
FROM autocomplete_airport
INNER JOIN autocomplete_airport_word
ON autocomplete_airport.id = autocomplete_airport_word.autocomplete_airport_id
WHERE lang = "pt"
AND word LIKE "yor%"
ORDER BY description
LIMIT 15

这个新结构值得麻烦吗?它真的会加快速度吗?有没有更简单的方法?

更新

刚注意到单词表有一个缺陷。结果:搜索“New York”不会给出任何结果。应该做什么:

term (with INDEX)                               | autocomplete_airport_id
------------------------------------------------+------------------------
New York - John F Kennedy (JFK), Estados Unidos | 123
York - John F Kennedy (JFK), Estados Unidos | 123
John F Kennedy (JFK), Estados Unidos | 123
F Kennedy (JFK), Estados Unidos | 123
Kennedy (JFK), Estados Unidos | 123
(JFK), Estados Unidos | 123
Estados Unidos | 123
Unidos | 123
JFK | 123

最佳答案

正如 MartinK 所说,如果您的表只有几百行,即使不进行优化,您的查询也应该非常快 - 值得检查发生了什么。

但是,搜索文本字段的最佳方法是使用全文索引 (http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) - 这是专为你描述的情况。

关于mysql - 提高 MySQL LIKE 查询的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9717190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com