简体   繁体   English

MySQL查询使用LIKE和通配符来匹配除空字符串之外的任何内容

[英]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. 我有一个名为images的表,它有一个字段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. 所以说文件名是image.jpg这很好,可以忽略,但如果文件名是image.jpg%3fhf43h408那么我需要删除这个图像。 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: 要识别包含文字'.jpg%' ,您可以使用:

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

To identify column values that do not end with the literal '.jpg' 识别不以文字'.jpg'结尾的列值

NOT LIKE '%.jpg'

or 要么

NOT REGEXP '\.jpg$'

Return all rows where image_filename does not end exactly in .jpg 返回image_filename不完全以.jpg结尾的所有行

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

The _ wildcard should match one character so try LIKE '%.jpg_%' . _通配符应匹配一个字符,因此请尝试LIKE '%.jpg_%'
It should match .jpg + 1 char + anything 它应匹配.jpg + 1 char + anything

Here is the reference: LIKE operator . 这是引用: LIKE运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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