前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SQL通配符

SQL通配符

作者头像
全栈程序员站长
发布2022-09-07 09:24:03
6410
发布2022-09-07 09:24:03
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

通常我们只是用 % 作为通配符,用来表示任意个字符。

但sql中的通配符还有 下划线 _ ,用来标识任意一个字符

实例

SELECT * FROM Websites WHERE name LIKE ‘_oogle’;

执行输出结果:

<span role="heading" aria-level="2">SQL通配符
<span role="heading" aria-level="2">SQL通配符

问题再延伸,如果我们数据中有包含下划线的字符,那么该怎么处理呢?

代码语言:javascript
复制
--需求,找到name中包含下划线的内容,即 把前两条筛出来
with x as
(select '_haha' as name from dual  union all
select '\_2haha'  as name from dual  union all
select '2haha' as name from dual
)
select * from x where name like '%_%';
<span role="heading" aria-level="2">SQL通配符
<span role="heading" aria-level="2">SQL通配符

不对,这里的下划线别理解成了通配符

代码语言:javascript
复制
-- 那么使用右斜杠+下划线的模式来转译他,可以么?
with x as
(select '_haha' as name from dual  union all
select '\_2haha'  as name from dual  union all
select '2haha' as name from dual
)
select * from x where name like '%\_%';
<span role="heading" aria-level="2">SQL通配符
<span role="heading" aria-level="2">SQL通配符

依然不对,这里斜杠并没有起到转译的作用。

查了下,自己以前不认识这个关键字。ESCAPE

代码语言:javascript
复制
-- 使用ESCAPE 关键字来表示【这个字符后边的东西,该被识别成普通字符。】?
with x as
(select '_haha' as name from dual  union all
select '\_2haha'  as name from dual  union all
select '2haha' as name from dual
)
select * from x where name like '%\_%' ESCAPE '\';
<span role="heading" aria-level="2">SQL通配符
<span role="heading" aria-level="2">SQL通配符

结果对了。那么换个别的字符呢?

代码语言:javascript
复制
with x as
(select '_haha' as name from dual  union all
select '\_2haha'  as name from dual  union all
select '2haha' as name from dual
)
select * from x where name like '%?_%' ESCAPE '?';
---

with x as
(select '_haha' as name from dual  union all
select '\_2haha'  as name from dual  union all
select '2haha' as name from dual
)
select * from x where name like '%!_%' ESCAPE '!';

结果都是

<span role="heading" aria-level="2">SQL通配符
<span role="heading" aria-level="2">SQL通配符

妥了。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155710.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档