Reputation: 417
Give a table User_DNA
and column a sequence
,
I want to write a query such that if data in the sequence
column matches or is prefix of the search query term, it should return an item found or true.
e.g,
sequence
dog
hor
cat
tig
cat
if my search query is doga
(has dog
as prefix in db), horrible
(has hor
as prefix in db),tiger
(has tig
as prefix in db), caterpillar
(has cat
as prefix in db), the query should return true
as all these search queries have prefixes in the database.
What should my sql search query?
Thanks
Upvotes: 0
Views: 79
Reputation: 5103
If you use Room, you can try this (using Kotlin):
@Query("select * from User_DNA WHERE sequence LIKE :search")
fun getItem(search: String): UserDNA?
Setting your search parameter to this method you should put the search pattern as "[your search string]%", for example: "dog%"
if my search query is dog, the query should return true or one of the items (dogsequence/doggysequence) what ever is efficient
You can check result of the query - if it's null, then there are no matching values in your column.
UPDATED
If you want to find "hor" with "horrible" I can propose next way (maybe it's a task for RegExp but honestly I haven't used it in ROOM):
Something like this:
@Query("select * from User_DNA WHERE sequence IN (:search) ORDER BY sequence")
fun getItem(search: List<String>): User_DNA?
fun findItem(search: String): User_DNA? {
val searchList = mutableListOf<String>()
val minimalStringLength = 2 // it's up to you, maybe 1?
while (search.length > minimalStringLength) {
searchList.add(search)
search = search.dropLast(1)
}
return getItem(searchList.toList())
}
Upvotes: 1