简体   繁体   中英

Using LIKE to search in SQL

I have an SQL query as below.

select *
from table 
where content like '%' + search_content + '%' 

If search_content = 'JAVA' , it will return data containing xxxJAVAxxx which is OK.

But if my search_content = 'JAVA ABC XYZ' , it is not returning data containing xxxJAVAxxx . Which is not a case I want.

How do I handle this situation?

Considering your example you can add the OR condition to cover all cases: the content contains, starts or endswith the desired string.

select *
from table 
where (content like '%JAVA%' or content like 'JAVA%' or content like '%JAVA')

A more elegant way (assuming you using postgres)

select *
from table
where position('JAVA' in content) > 0

What it does? It finds the position where the 'JAVA' substring can be found in content. If the substring exists the positon is higher that 0.

You can find an equivalent functions in SQL Server.

select *
from table
where CHARINDEX('JAVA', content) > 0

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