3

I am using MySQL Workbench and I'm currently looking for a function or something that helps me check if a string is within another string. For example:

text1 = 'hello , name , world';

If I have a string or varchar that is something like this

'My name is'

It should say that it contains since it has 'name' on it. Basically what I'm trying to do is I have a Comments table and I'm creating a trigger before insert on Comments that checks if the comment_text contains any swear words. These swear words are saved like this

select group_concat(word) into texto from reserved_words;

So it has all the words close to each other: swear1,swear2,swear3,etc

I want it to update a certain table if the comment really contains a swear word. I've tried to use LIKE, SUBSTR(),CONTAINS(),REGEXP without any success.

Can someone help?

2
  • Can you put some example queries with data out here so we know what you tried? Commented Jun 23, 2018 at 2:25
  • Were you able to achieve the desired result ? Please see What should I do when someone answers my question?. Commented Jul 11, 2018 at 15:16

3 Answers 3

12

LIKE is what you want. You need to wrap it with % to match anywhere in the string.

WHERE string LIKE '%name%'

will be true if the value of the string column contains the string name.

If you have the swear words in a column of a table, you can join them:

SELECT DISTINCT comment
FROM comments AS c
JOIN swear_words AS s ON c.comment LIKE CONCAT('%', s.word, '%')

Don't put the swear words into a comma-separated list, that makes it very difficult to work with them individually in MySQL.

Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest:

where comment regexp replace(swearwords, ',', '|')

You may or may not want to include word delimiters in the regular expression pattern.

Comments

0

Build your regex pattern from reserved_words table:

select CONCAT('(',group_concat(word SEPARATOR '|'),')') from reserved_words

And then run REGEXP check against the comment field.

DEMO RUN

create table reserved_words(word varchar(10));
insert into reserved_words values('hello'),('name'),('world');

select 'My name is' REGEXP (select CONCAT('(',group_concat(word SEPARATOR '|'),')') from reserved_words) swear
UNION ALL
select 'My title is' REGEXP (select CONCAT('(',group_concat(word SEPARATOR '|'),')') from reserved_words) swear
UNION ALL
select 'hello world' REGEXP (select CONCAT('(',group_concat(word SEPARATOR '|'),')') from reserved_words) swear;

RESULT

swear
1
0
1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.