[英]sql search in only parts of a string
I have a comma separated list of names in a database called owners (sometimes there is one owner sometimes there are multiple owners... if there are more than 1 the names are comma separated). 我在数据库中有一个用逗号分隔的名称列表,称为所有者(有时有一个所有者,有时会有多个所有者...如果名称多于1,则用逗号分隔)。 I want to find whether a certain name appears as the first name in the owners field.
我想查找某个名称是否显示为所有者字段中的名字。 So I need to search for a pattern as eg with the like command in sql, but I need to restrict it to the part before the first comma.
因此,我需要使用sql中的like命令来搜索模式,但是我需要将其限制在第一个逗号之前的部分。 Note that I want that the entry
请注意,我要输入
John Doe, Katrin 约翰·多伊,卡特琳
is found if my pattern is "John". 如果我的模式是“ John”,则会被发现。 Is that possible at all?
那有可能吗? I am looking for a solution in sqlalchemy, but if there is a solution in sql I am sure I can find the sqlalchemy version myself.
我在sqlalchemy中寻找解决方案,但是如果在sql中有解决方案,我可以确定自己可以找到sqlalchemy版本。 thanks carl
谢谢卡尔
In SQL server, you could do: 在SQL Server中,您可以执行以下操作:
select colname
where substring(lower(colname), 1, charindex(',',lower(colname))-1) like '%john%'
You could do the same in Oracle as 您可以在Oracle中做与
select colname
where substr(lower(colname), 1, instr(lower(colname),',')-1) like '%john%'
As you can see the functions are specific to databases. 如您所见,这些功能特定于数据库。
You can get away with using LIKE
as it is as the front of the string. 您可以直接使用
LIKE
作为字符串的开头。 The %
match anything. %
匹配任何内容。 Here it is in sqlalchemy
这是在
sqlalchemy
session.query(Object).filter(Object.column.like('THENAME,%'))
If you want to match just "Jon Doe" with just "Jon" you will need a regex 如果您只想将“ Jon Doe”与“ Jon”进行匹配,则需要使用正则表达式
session.query(Object).filter(Object.column.op('regexp')('r^Jon[^,]*,'))
This will match anything starting ^
with Jon
followed by any number of non ,
chars [^,]*
followed by ,
这将匹配以
Jon
开头的^
,后跟任意数量的non ,
char [^,]*
后跟,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.