MySQL:为什么在 LIKE 运算符中转义不起作用? [英] MySQL: Why is does escaping not working in the LIKE operator?

查看:129
本文介绍了MySQL:为什么在 LIKE 运算符中转义不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 MySQL 8.0 中使用模式匹配字符串:

I'm experimenting with pattern matching strings in MySQL 8.0:

CREATE TABLE foo (bar VARCHAR(250));

INSERT INTO `foo` (`bar`) VALUES ('\%');

作为练习,我想使用 LIKE 编写一个特定查询,该查询返回类似于文字 \%"的行.(我知道这实际上应该通过 = 比较来完成,但这是一个练习)

As an exercise, I'd like to write a specific query using LIKE that returns rows that are "like the literal \%". (I know this is should actually be done with = comparison but this is an exercise)

  1. 由于 % 是通配符,我不能简单地使用:

  1. As % is a wildcard character, I cannot simply use:

SELECT * from `foo` WHERE `bar` LIKE '\%';

当我尝试使用默认转义字符 \ 进行转义时,它也失败了:

When I try to escape using the default escape character \ it also fails:

SELECT * from `foo` WHERE `bar` LIKE '\\%';

同样,当我尝试使用 ESCAPE 关键字来定义非默认转义字符时:

And likewise when I tryin to use the ESCAPE keyword to define a non-default escape character:

SELECT * from `foo` WHERE `bar` LIKE '\|%' ESCAPE '|';

为什么查询 2 和 3 对我不起作用?

推荐答案

三个很简单.

% 不是通配符,它​​只是一个像其他字符一样的字符

% is not a wildcard is t simply a character like every character else

SELECT * from `foo` WHERE `bar` LIKE '\%' ESCAPE '|';

工作正常

第二个也有效.

但是你需要

SELECT * from `foo` WHERE `bar` LIKE '\\\%';

我记得你必须逃脱转义和通配符!

I remember You have to escape the escape and the wildcard!

这篇关于MySQL:为什么在 LIKE 运算符中转义不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆