作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 USERSEARCH 表,应该用于用户的快速子字符串搜索。此功能用于在有人输入用户名或姓名时进行的自动完成搜索。但是,我感兴趣的查询只会显示搜索者所关注的用户子集的匹配项。这可以在USERRELATIONSHIP 表中找到。
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
SELECT * FROM myapp.usersearch where username_ngram like 'Al%'
UNION DISTINCT
SELECT * FROM myapp.usersearch where name_ngram like 'Al%'
UNION DISTINCT
SELECT * FROM myapp.usersearch
WHERE MATCH (username_ngram, name_ngram) AGAINST ('Al')
LIMIT 10
WITH
--Part 1, restrict the USERSEARCH table to just the users that are followed by searcher
tempUserSearch AS (SELECT T1.id, T2.username_ngram, T2.name_ngram FROM
(SELECT follows_id FROM myapp.userrelationship WHERE user_id = {user_idOfSearcher} ) AS T1
LEFT JOIN myapp.usersearch AS T2 ON T2.user_id = T1.follows_id)
SELECT * FROM tempUserSearch where username_ngram like 'Al%'
UNION DISTINCT
SELECT * FROM tempUserSearch where name_ngram like 'Al%'
UNION DISTINCT
SELECT * FROM tempUserSearch
WHERE MATCH (username_ngram, name_ngram) AGAINST ('Al')
LIMIT 10
index(username_ngram)
index(name_ngram)
FULLTEXT(username_ngram, name_ngram)
最佳答案
MySQL 5.7 不支持普通表表达式; WITH
语法仅在 8.0 版中可用。
由于您现有的查询运行速度很快,因此在外部查询中进行过滤可能是可行的解决方案:
SELECT ur.id, ng.username_ngram, ng.name_ngram
FROM myapp.userrelationship ur
INNER JOIN (
SELECT * FROM myapp.usersearch WHERE username_ngram LIKE 'Al%'
UNION DISTINCT
SELECT * FROM myapp.usersearch WHERE name_ngram LIKE 'Al}%'
UNION DISTINCT
SELECT * FROM myapp.usersearch WHERE MATCH (username_ngram, name_ngram) AGAINST ('Al')
) ng ON ng.user_id = ur.follows_id
WHERE ur.user_id = {user_idOfSearcher}
ORDER BY ??
LIMIT 10
LEFT JOIN
到 INNER JOIN
因为我认为这更接近你想要的(如果它不符合你的要求,你可以把它改回来)ORDER BY
条款一起去LIMIT
,否则当结果集中的行数超过 10 行时,结果不确定 关于mysql - 如何在 MySQL 5 .7 中实现 CTE 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479503/
我是一名优秀的程序员,十分优秀!