mysql中利用select查询某字段中包含以逗号分隔的字符串的记录方法 首先我们建立一张带有逗号分隔的字符串。 create table test(id int(6) not null auto_increment,primary key (id),pname varchar(20) not null,pnum varchar(50) not null); 然后插入带有逗
mysql中利用select查询某字段中包含以逗号分隔的字符串的记录方法
首先我们建立一张带有逗号分隔的字符串。create table test(id int(6) not null auto_increment,primary key (id),pname varchar(20) not null,pnum varchar(50) not null);
然后插入带有逗号分隔的测试数据
insert into test(pname,pnum) values('产品1','1,2,4');
insert into test(pname,pnum) values('产品2','2,4,7');
insert into test(pname,pnum) values('产品3','3,4');
insert into test(pname,pnum) values('产品4','1,7,8,9');
insert into test(pname,pnum) values('产品5','33,4');
查找pnum字段中包含3或者9的记录
mysql> select * from test where find_in_set('3',pnum) or find_in_set('9',pnum);
+----+-------+---------+
| id | pname | pnum? |
+----+-------+---------+
|? 3 | 产品3 | 3,4 |
|? 4 | 产品4 | 1,7,8,9 |
+----+-------+---------+
2 rows in set (0.03 sec)
使用正则
mysql> select * from test where pnum regexp '(3|9)';
+----+-------+---------+
| id | pname | pnum? |
+----+-------+---------+
|? 3 | 产品3 | 3,4 |
|? 4 | 产品4 | 1,7,8,9 |
|? 5 | 产品5 | 33,4? |
+----+-------+---------+
3 rows in set (0.02 sec)
这样会产生多条记录,比如33也被查找出来了,不过mysql还可以使用正则,挺有意思的
find_in_set()函数返回的所在的位置,如果不存在就返回0
mysql> select find_in_set('e','h,e,l,l,o');
+------------------------------+
| find_in_set('e','h,e,l,l,o') |
+------------------------------+
|? 2 |
+------------------------------+
1 row in set (0.00 sec)
还可以用来排序,如下;
mysql> select * from test where id in(4,2,3);
+----+-------+---------+
| id | pname | pnum? |
+----+-------+---------+
|? 2 | 产品2 | 2,4,7 |
|? 3 | 产品3 | 3,4 |
|? 4 | 产品4 | 1,7,8,9 |
+----+-------+---------+
3 rows in set (0.03 sec)
如果想要按照id为4,2,3这样排序呢?
mysql> select * from test where id in(4,2,3) order by find_in_set(id,'4,2,3');
+----+-------+---------+
| id | pname | pnum? |
+----+-------+---------+
|? 4 | 产品4 | 1,7,8,9 |
|? 2 | 产品2 | 2,4,7 |
|? 3 | 产品3 | 3,4 |
+----+-------+---------+
3 rows in set (0.03 sec)?
http://www.itokit.com/2012/0606/74328.html