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)
其实啊,你不仅写'1,2'会查出三条数据,就算你写'1ncdsln'或者'1ncskl12397na'之类的也会查出三条,就是Department 等于1的那三条,因为Department是bigint类型,但是你查的时候写的是字符串,这时候mysql就会去字符串前面的数字部分来查询,'312你打开所老'就会截取312这样,因为你的'1,2'不是bigint类型,所以会截取前面的数字,即1来查欢迎分享,转载请注明来源:内存溢出
评论列表(0条)