MYSQL uses select to query records that contain comma-separated strings in a field

Reprinted from: http://www.2cto.com/database/201409/330107.html

First we create a string separated by commas.
CREATE TABLE test(id int(6) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),pname VARCHAR(20) NOT NULL,pnum VARCHAR(50) NOT NULL);

Then insert test data with comma separated
INSERT INTO test(pname,pnum) VALUES('Product 1','1,2,4');
INSERT INTO test(pname,pnum) VALUES('Product 2','2,4,7');
INSERT INTO test(pname,pnum) VALUES('Product 3','3,4');
INSERT INTO test(pname,pnum) VALUES('Product 4','1,7,8,9');
INSERT INTO test(pname,pnum) VALUES('Product 5','33,4');

Find records that contain 3 or 9 in the pnum field
mysql> SELECT * FROM test WHERE find_in_set('3',pnum) OR find_in_set('9',pnum);
+----+-------+---------+
| id | pname | pnum    |
+----+-------+---------+
| 3 | Product 3 | 3,4 |
| 4 | Product 4 | 1,7,8,9 |
+----+-------+---------+
2 rows in set (0.03 sec)


use regular
mysql> SELECT * FROM test WHERE pnum REGEXP '(3|9)';
+----+-------+---------+
| id | pname | pnum    |
+----+-------+---------+
| 3 | Product 3 | 3,4 |
| 4 | Product 4 | 1,7,8,9 |
| 5 | Product 5 | 33,4 |
+----+-------+---------+
3 rows in set (0.02 sec)
This will generate multiple records, such as 33 is also found, but MYSQL can also use regular, very interesting

The position returned by the find_in_set() function, or 0 if it does not exist
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)

It can also be used to sort, as follows;
mysql> SELECT * FROM TEST WHERE id in(4,2,3);
+----+-------+---------+
| id | pname | pnum    |
+----+-------+---------+
| 2 | Product 2 | 2,4,7 |
| 3 | Product 3 | 3,4 |
| 4 | Product 4 | 1,7,8,9 |
+----+-------+---------+
3 rows in set (0.03 sec)

What if you want to sort by 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 | Product 4 | 1,7,8,9 |
| 2 | Product 2 | 2,4,7 |
| 3 | Product 3 | 3,4 |
+----+-------+---------+
3 rows in set (0.03 sec)

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992615&siteId=291194637