Mysql lookup how to judge whether a field contains a certain string

Mysql search how to judge whether a field contains a certain string

There is such a requirement. In the Mysql database string field (permission), the user has multiple different mailboxes, which are separated by ','. Now we need to extract all the mailboxes of a certain mailbox. Member list.

Suppose there is a table:

CREATE TABLE users(id int(6) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),user_name VARCHAR(20) NOT NULL,emails VARCHAR(50) NOT NULL);


Initialize the table and add some records.
 
truncate table users
INSERT INTO users(user_name, emails) VALUES('小张','[email protected],[email protected],[email protected]');
INSERT INTO users(user_name, emails) VALUES('小王','[email protected],[email protected],[email protected]');


Some fields in Mysql are of string type. How to find records that contain certain characters?

Method 1

is very simple and can be implemented with %. For

example ,

SELECT * FROM users WHERE emails like "%[email protected]%";


but in this case, [email protected] will also be found, which does not meet the requirements.

Method 2

Use the mysql string function find_in_set();

SELECT * FROM users WHERE find_in_set('[email protected]', emails);


In this way, all users whose email field contains

[email protected] The effect we expected, the problem is solved!

It should be noted that the mysql string function find_in_set(str1, str2) function returns the position index of str1 in str2, and str2 must be separated by ",".

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326828304&siteId=291194637