简体   繁体   中英

MySQL query using LIKE and a wildcard to match anything but empty string

I have a table called images which has a field image_filename. I have noticed that some images that have been stored have characters after the file extension and these do not load properly. So say the filename is image.jpg this is fine and can be ignored, however if the filename is image.jpg%3fhf43h408 then I need to delete this image. This is my query so far to try and select all of the images that have stuff after the extension:

SELECT `images`.* FROM images
WHERE `images`.`image_filename` LIKE '%.jpg\%' 

This returns all images though even if there is nothing after the extension. How do I get the query to only return images where there is something after the extension. To add extra confusion the stuff after the extension seems to always begin with a percentage sign hence why I am trying to escape it in my query to be treated as a literal percentage sign rather than a wildcard. I have tried the following also:

SELECT `images`.* FROM images
WHERE `images`.`image_filename` LIKE '%.jpg\%' escape '\'

But this doesn't work and it just says I have an error

To get the backslash identified as the escape character, you need to use double backslashes to represent a single backslash.

You also need a wildcard % to match the remainder of the string.

To identify rows that contain a literal '.jpg%' , you could use this:

LIKE '%.jpg\%%' ESCAPE '\\'

To identify column values that do not end with the literal '.jpg'

NOT LIKE '%.jpg'

or

NOT REGEXP '\.jpg$'

Return all rows where image_filename does not end exactly in .jpg

SELECT `images`.* 
FROM images
WHERE `images`.`image_filename` NOT LIKE '%.jpg' 

The _ wildcard should match one character so try LIKE '%.jpg_%' .
It should match .jpg + 1 char + anything

Here is the reference: LIKE operator .

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