Postgresql SELECT如果字符串包含

axkjgtzd  于 2022-12-12  发布在  PostgreSQL
关注(0)|答案(5)|浏览(171)

So I have a in my Postgresql:

TAG_TABLE
==========================
id            tag_name       
--------------------------
1             aaa
2             bbb
3             ccc

To simplify my problem, What I want to do is SELECT 'id' from TAG_TABLE when a string "aaaaaaaa" contains the 'tag_name'. So ideally, it should only return "1", which is the ID for tag name 'aaa'
This is what I am doing so far:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaaaaa' LIKE '%tag_name%'

But obviously, this does not work, since the postgres thinks that '%tag_name%' means a pattern containing the substring 'tag_name' instead of the actual data value under that column.
How do I pass the tag_name to the pattern??

uz75evzq

uz75evzq1#

应该在引号外使用tag_name;则将其解释为记录的字段。使用带有文字百分号的'||'进行连接:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';

请记住,LIKE是区分大小写的。如果需要不区分大小写的比较,可以这样做:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || LOWER(tag_name) || '%';
jbose2ul

jbose2ul2#

查找子字符串的正确方法是使用position函数而不是like表达式,like表达式需要转义%_和一个转义字符(默认为\):

SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
wsewodh2

wsewodh23#

我个人更喜欢~运算符的简单语法。

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;

值得通过阅读Difference between LIKE and ~ in Postgres来了解两者的区别。

yfjy0ee7

yfjy0ee74#

除了'aaaaaaaa' LIKE '%' || tag_name || '%'的解决方案之外,还有position(颠倒了args的顺序)和strpos

SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0

除了效率更高之外(LIKE看起来效率较低,但索引可能会改变一些事情),LIKE还有一个非常小的问题:tag_name当然不应包含%,尤其是_(单字符通配符),以给予误报。

42fyovps

42fyovps5#

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';

tag_name should be in quotation otherwise it will give error as tag_name doest not exist

相关问题