PostgreSQL:如何仅显示列中匹配搜索字符串的目标内容片段
实现PostgreSQL查询仅返回第一个匹配关键词的后续截断内容
现有guidelines表结构及数据如下:
Table name: guidelines id content 1 An individual is accused “of” a crime, not “with” or “for” a crime. Accused, often as “the accused”, refers to the individual or individuals standing trial. EXAMPLES: The prosecutor accused the politician of bribery. The accused politician stood trial for bribery. See alleged, charged, suspected. 2 There were a lot of people getting accused on this particular town.
原查询语句(修正语法错误后)会返回完整的content内容:
SELECT content FROM "guidelines" WHERE "content" ILIKE '%accused%';
要实现仅返回第一个匹配的accused(不区分大小写)及其后续内容,并截断添加省略号,可使用以下SQL:
SELECT CASE WHEN length(substring(content FROM position(lower('accused') IN lower(content)))) > 30 THEN concat(left(substring(content FROM position(lower('accused') IN lower(content))), 30), '...') ELSE substring(content FROM position(lower('accused') IN lower(content))) END AS content FROM guidelines WHERE content ILIKE '%accused%';
语句说明:
position(lower('accused') IN lower(content)):将关键词和内容统一转为小写,找到第一个accused(不区分大小写)在内容中的起始位置,确保匹配不区分大小写。substring(content FROM ...):从匹配位置开始截取原内容的后续部分,保留原文本的大小写格式。left(..., 30):截取前30个字符(可根据需求调整这个数字),控制返回内容的长度。CASE语句:判断截取后的内容长度,超过指定长度则添加省略号,否则直接返回截取内容。
执行上述语句后,返回结果示例:
content accused “of” a crime, not “with” or “f... accused on this particular town.
如果需要匹配后的内容从关键词首字母大写的位置开始(如示例中的Accused, often as...),可调整关键词为Accused并去掉lower()转换,但这样会区分大小写匹配。
内容的提问来源于stack exchange,提问作者radren
相关产品推荐
相关产品推荐

