PostgreSQL:如何修改查询实现unaccent与大小写不敏感匹配
解决PostgreSQL查询匹配大小写和重音变体的问题
问题原因
你当前的查询仅对目标字符串'Révolut'做了去重音和转小写处理,但未对字段intitule执行去重音操作。比如字段值为'révolut'时,LOWER(intitule)得到的是带重音的'révolut',而LOWER(unaccent('Révolut'))得到的是无重音的'revolut',两者无法匹配。
修改方案
方案一:对字段和目标字符串都做去重音+转小写处理
将intitule也通过unaccent函数去除重音后再转小写,确保两边格式完全一致:
select * from entrees where account_id = 1 and categorie_id = 2 and recurrent = false and montant < 0 and ABS(montant) >= 50000 and date_de_valeur >= '2025-05-01' and date_de_valeur < '2025-06-01' and LOWER(unaccent(intitule)) = LOWER(unaccent('Révolut'));
方案二:使用ILIKE结合unaccent实现匹配
如果只需要完全匹配但忽略大小写和重音,也可以用ILIKE配合去重音,写法更简洁:
select * from entrees where account_id = 1 and categorie_id = 2 and recurrent = false and montant < 0 and ABS(montant) >= 50000 and date_de_valeur >= '2025-05-01' and date_de_valeur < '2025-06-01' and unaccent(intitule) ILIKE unaccent('Révolut');
额外说明
- 确保PostgreSQL已安装
unaccent扩展,未安装的话先执行:CREATE EXTENSION IF NOT EXISTS unaccent; - 若需频繁执行这类查询,建议给
LOWER(unaccent(intitule))创建函数索引提升效率:CREATE INDEX idx_entrees_intitule_unaccent ON entrees (LOWER(unaccent(intitule)));
内容的提问来源于stack exchange,提问作者thiebo
相关产品推荐
相关产品推荐

