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??
5条答案
按热度按时间uz75evzq1#
应该在引号外使用
tag_name
;则将其解释为记录的字段。使用带有文字百分号的'||'
进行连接:请记住,
LIKE
是区分大小写的。如果需要不区分大小写的比较,可以这样做:jbose2ul2#
查找子字符串的正确方法是使用
position
函数而不是like
表达式,like
表达式需要转义%
、_
和一个转义字符(默认为\
):wsewodh23#
我个人更喜欢
~
运算符的简单语法。值得通过阅读Difference between LIKE and ~ in Postgres来了解两者的区别。
yfjy0ee74#
除了
'aaaaaaaa' LIKE '%' || tag_name || '%'
的解决方案之外,还有position
(颠倒了args的顺序)和strpos
。除了效率更高之外(LIKE看起来效率较低,但索引可能会改变一些事情),LIKE还有一个非常小的问题:tag_name当然不应包含
%
,尤其是_
(单字符通配符),以给予误报。42fyovps5#
tag_name
should be in quotation otherwise it will give error as tag_name doest not exist