I have a USERSEARCH table that should be used for fast substring searches for users. This feature is for an autocomplete search that occurs while someone is typing for a username or name. However, the query I am interested in will only show matches from users the person follows.
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
The following query is performed as someone has just typed "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
Indices
index(user_id)
index(username_ngram)
index(name_ngram)
FULLTEXT(username_ngram, name_ngram)
Is there a way to restrict the above query to only look at this subset of user_ids (without querying for them 3 times for each subquery)?
SELECT follows_id FROM rage.userrelationship WHERE user_id={user_id of user doing the searching}