You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL:如何查询与指定字符串结尾匹配的记录?

PostgreSQL查询:获取字段值为指定字符串后缀的记录

给定以下PostgreSQL表结构和数据:

CREATE TABLE sample(id int, identity varchar(20));
INSERT INTO sample (id,identity) VALUES (1,'9822');
INSERT INTO sample (id,identity) VALUES (2,'129822');
INSERT INTO sample (id,identity) VALUES (3,'ABCD9822');
INSERT INTO sample (id,identity) VALUES (4,'1234');

要筛选出identity字段值为字符串0987129822后缀的记录,有两种常用实现方式:

方法1:使用RIGHT函数匹配后缀

通过RIGHT函数从目标字符串右侧截取与identity长度一致的子串,再与identity字段比较:

SELECT id, identity
FROM sample
WHERE RIGHT('0987129822', LENGTH(identity)) = identity;

方法2:使用LIKE操作符匹配

利用通配符%构造匹配模式,判断目标字符串是否以identity结尾:

SELECT id, identity
FROM sample
WHERE '0987129822' LIKE '%' || identity;

执行结果

两种方法都会返回符合要求的记录:

id | identity 
----+----------
  1 | 9822
  2 | 129822

注:记录3的ABCD9822因与目标字符串后缀不匹配会被排除;记录4的1234同样不符合条件。

内容的提问来源于stack exchange,提问作者mah454

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:53:20