Mysql string field two methods to determine whether a string is contained _ MySQL

Source: Internet
Author: User
This article mainly introduces two methods for determining whether Mysql string fields contain a certain string. This article uses the Like and find_in_set methods to achieve this. For more information, see the following table:

The code is as follows:


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.

The code is as follows:


Truncate table users
Insert into users (user_name, emails) VALUES ('login', 'A @ email.com, B @email.com, c@email.com ');
Insert into users (user_name, emails) VALUES ('king', 'AA @ email.com, bb@email.com, cc@email.com ');

  

In Mysql, some fields are of the string type. how do I find records containing some characters?

Method 1:

The code is as follows:


SELECT * FROM users WHERE emails like "% B @email.com % ";

So the bb@email.com user also found out, not in line with expectations.

Method 2:

Use the mysql string function find_in_set ();

The code is as follows:


SELECT * FROM users WHERE find_in_set ('AA @ email.com ', emails );

  

This is acceptable. how can this problem be solved?

Mysql has many string functions: find_in_set (str1, str2) returns the index of the position of str1 in str2. str2 must be separated by commas.

E.g.

The code is as follows:


Mysql> SELECT find_in_set () ('B', 'a, a, B, c, D') as test;
-> 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.