Home > Database > Mysql Tutorial > body text

Mysql字符串字段判断是否包含某个字符串的2种方法

WBOY
Release: 2016-06-07 16:28:54
Original
742 people have browsed it

假设有个表: CREATE TABLE users(id int(6) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),user_name VARCHAR(20) NOT NULL,emails VARCHAR(50) NOT NULL); 初始化表,并添加些记录。 truncate table users INSERT INTO users(user_name, emails) VALUES('小张

假设有个表:


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

初始化表,并添加些记录。 


truncate table users
INSERT INTO users(user_name, emails) VALUES('小张','a@email.com,b@email.com,c@email.com');
INSERT INTO users(user_name, emails) VALUES('小王','aa@email.com,bb@email.com,cc@email.com');

  

Mysql 中有些字段是字符串类型的,如何查找其中包含某些字符的记录呢?

方法一:


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

这样bb@email.com的用户也查出来了,不符合预期。

方法二:

利用mysql 字符串函数 find_in_set();


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

  

这样是可以的,怎么理解呢?

mysql有很多字符串函数 find_in_set(str1,str2)函数是返回str2中str1所在的位置索引,str2必须以","分割开。

e.g.


mysql > SELECT find_in_set()('b','a,a,b,c,d') as test;
-> 3

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template