简体   繁体   中英

MySQL SELECT first letter of the words sequentially for searching

Sample words:

iknkr st nm krt prk
iknkr vhgr j k pth  
iknkr hkm st
iknkr sr vhgr j k pth

Required Condition

Now, if a user types: ik s the query will return:

iknkr st nm krt prk 
iknkr sr vhgr j k pth

if a user types: iv the query will return:

iknkr vhgr j k pth

Currently Trying:

SELECT `walpha` AS word, pageID AS id 
FROM `SX01` 
WHERE `table`= 'S01' 
  AND `walpha` like '" . $this->db->escape_like_str($searchVal['keyword']) . "%' 
LIMIT 100"

But using this user have to type: iknkr s

to get the result

iknkr st nm krt prk 
iknkr sr vhgr j k pth

Can anyone suggest, what will be the right way of doing it.

You could build a regular expression from the input and then use REGEXP to have MySQL use it. For example, you could turn ik s into ^ik[az]* s to match words which which start with ik followed by a word starting with s ...

SELECT words FROM tbl WHERE t.words REGEXP '^ik[a-z]* s';
  • ^ means we must match from the start of the string
  • ik must then be the first two chars
  • [az] will match any lowercase alphabetic char
  • * allows us to match zero or more of the previous pattern - ie any sequence of chars can follow ik
  • then must have a space
  • s followed by an s - we don't care about what follows.

You can build this pattern from the user input by replacing all spaces with [az]* and prefixing with ^

If I understand your logic correctly, you could try with a query like this:

select `walpha` AS word, pageID AS id
from `SX01` 
where
  `table`= 'S01' 
  and `walpha` like concat(replace('" . $yoursearchval . "', ' ', '% '), '%') 
limit 100

for example:

concat(replace('i k', ' ', '% '), '%')

will become:

i% k%

but if you want the words to be consecutive, you'll have to use a regular expression:

where whalpa regexp concat('^', replace('i k', ' ', '[^[:space:]]+ '))

and ik will become:

^i[^[:space:]]+ k
  • the string has to start with i
  • after i there has to be at least + one non space character
  • then one space
  • then one k
  • then anything else

select id,title,upper(left(title,1)) AS FirstLetter from store order by title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM