MYSQL中利用select查詢某欄位中包含以逗號分隔的字串的記錄方法,mysqlselect
首先我們建立一張帶有逗號分隔的字串。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()函數返回的所在的位置,如果不存在就返回0mysql> 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)
MYSQL怎查詢某TEXT欄位裡包含特定字串的所有記錄
select * from tables where fied like '%AAAAA%';
mysql查詢欄位包含在字串內的記錄
select * from robot where instr('ABCD',key)>0