1. 程式人生 > >MYSQL中模糊查詢帶逗號間隔的字元(FIND_IN_SET)

MYSQL中模糊查詢帶逗號間隔的字元(FIND_IN_SET)

首先我們建立一張帶有逗號分隔的字串。  
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)