简体   繁体   中英

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). 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. Note that I want that the entry

John Doe, Katrin

is found if my pattern is "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. thanks carl

In SQL server, you could do:

select colname
where substring(lower(colname), 1, charindex(',',lower(colname))-1) like '%john%'

You could do the same in Oracle as

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. The % match anything. Here it is in 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

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 ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM