简体   繁体   中英

MySQL Regexp won't work

I have the following query:

SELECT  `admin_users`.* 
FROM `admin_users` 
WHERE (avatar REGEXP 'avatars/Name-[0-9]+.jpg+')  
ORDER BY `admin_users`.`avatar` 
DESC LIMIT 1

It's ok if I have something like:

  • avatars/Name-5.jpg
  • avatars/Name-6.jpg

But if I have, avatars/Name-15.jpg , for example, it doesn't return in query.

In other words, It only works for 1 digit, not for more. How can I solve it?

When comparing strings (an that is what avatar is), "avatars/Name-1..." comes before "avatars/Name-5..." simply because the string "1" comes before "5".

It is not practical to order those by an embedded number. This would do what you want, but it is pretty cryptic:

ORDER BY 0 + MID(avatar, 14)

To explain

  1. MID will start at the 14th character of 'avatars/Name-15.jpg' and extract '15.jpg'.
  2. 0+ will take that string, convert it to a number and deliver the number 15. (When a string is turned into a number, the first characters are taken as long as it looks like a number. So, 0+'abc' will deliver 0 , since there is nothing at the beginning of abc that looks like a number.)

If the left part were not exactly 14 characters in all cases, the trick will fail. And it may get so complicated as to be 'impossible' in SQL.

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