Suppose I have the following SQL query:
SELECT
id, text
FROM
comments
WHERE
lower(text) LIKE '%hell%'
ORDER BY len(text) ASC
This matches any text that contains hell
. However, I want to exclude a particular word from a match: "seashells". How can I write an SQL query that matches everything that contains hell
, but ignores seashells
?
Examples:
You could try keeping your current logic but checking for %hell%
after first removing seashells
from the text:
SELECT id, text
FROM comments
WHERE LOWER(REPLACE(text, 'seashell', '')) LIKE '%hell%'
ORDER BY LEN(text);
Note that regex search would be a much better way to handle your requirement, but SQL Server does not have much built in regex support.
You can try Not Like
in Sql Query. Here is something you can try.
SELECT
id, text
FROM
comments
WHERE
lower(text) LIKE '%hell%'
ORDER BY len(text) ASC
EXCEPT
SELECT
id, text
FROM
comments
WHERE
lower(text) LIKE '%seashells%'
OR
lower(text) LIKE '%other_word%'
ORDER BY len(text) ASC
To exclude some specific key word containing hell . Note: NOT / LIKE IS CASE SENSITIVE.
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.