简体   繁体   中英

How to select the substring of a filename in MySQL?

I'm doing an autocomplete to find files matching a search parameter entered in a form. If someone enters "p" it returns ALL pdf files, which I don't want. I only want them to search the name of the file. Here's my query...

SELECT uid, link_text 
FROM tblProfile 
WHERE link_text LIKE "%'. $text . '%"
ORDER BY link_text
LIMIT 8

I tried to do...

SELECT SUBSTRING(link_text,-4,4)
FROM tblProfile
WHERE SUBSTRING(link_text,-4,4) like "%'. $text . '%"

But it didn't work. I could create a new column in the table to store the name w/out the extension but there has to be a better way!

assuming all your file names have only one dot (no filenames like my.file.pdf) you can use substring_index:

SELECT SUBSTRING_INDEX(link_text,'.',1) AS fname
FROM tblProfile
WHERE fname like "%'. $text . '%"

This may be slow although, so consider one of these options:

  1. Store the filename without extension in a separate column and index it (gives you a performance boost!)

  2. Modify your query to WHERE link_text LIKE "' . $text . '%" so you start at the beginning of the file name.

If you want the part of the filename except the extension (eg only 'abc' out of abc.pdf), you can search the '.' in the same, get its index directly and do substring on the filename like SUBSTR(filename, 0, <position of '.'> - 1)

Please refer http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index for better explanation.

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