开发者

How to select the substring of a filename in MySQL?

开发者 https://www.devze.com 2023-03-05 10:52 出处:网络
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 na

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开发者_如何学JAVA
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!


Try with SUBSTRING_INDEX().

Example: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index


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 (e.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消