【发布时间】:2020-10-10 03:38:52
【问题描述】:
我有一个 USERSEARCH 表,应该用于快速搜索用户的子字符串。此功能适用于在有人输入用户名或名称时发生的自动完成搜索。但是,我感兴趣的查询只会显示该人关注的用户的匹配项。
USERSEARCH
-----------------------------------------------
user_id(FK) username_ngram name_ngram
1 "AleBoy leBoy eBoy..." "Ale le e"
2 "craze123 raze123 ..." "Craze raze aze ze e"
3 "john1990 ohn1990 ..." "John ohn hn n"
4 "JJ_1 J_1 _1 1" "JJ"
USERRELATIONSHIP
-----------------------------------------------
user_id(FK) follows_id(FK)
2 1
2 3
以下查询在某人刚刚输入“Al”时执行:
SELECT * FROM rage.usersearch where username_ngram like 'Al%' --1
UNION DISTINCT
SELECT * FROM rage.usersearch where name_ngram like 'Al%' --2
UNION DISTINCT
SELECT * FROM rage.usersearch --3
WHERE MATCH (username_ngram, name_ngram) AGAINST ('Al')
LIMIT 10
指数
index(user_id)
index(username_ngram)
index(name_ngram)
FULLTEXT(username_ngram, name_ngram)
有没有办法限制上述查询只查看 user_ids 的这个子集(每个子查询不查询 3 次)?
SELECT follows_id FROM rage.userrelationship WHERE user_id={user_id of user doing the searching}
【问题讨论】:
-
全文索引不适用于 LIKE。搜索“UNION 优化”。
-
@PaulSpiegel 像我提到的两个正常指数怎么样?我知道他们帮助 LIKE {string}%
-
这可能会有所帮助:sql-performance-union-vs-or
-
LIKE '{string}%'是范围搜索。 MySQL 无法对一个索引执行两次(有效)范围搜索。 -
此 LIMIT 作用于完整的 UNION 集。请参阅UNION Clause“要将 ORDER BY 或 LIMIT 子句应用于单个 SELECT,请将 SELECT 括起来并将子句放在括号内”。你没有 - 所以它作用于全套。
标签: mysql sql database database-design database-indexes