Create the table:
1 CREATE TABLE users(id int(6) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(20) NOT NULL,limits VARCHAR(50) NOT NULL);
adding data:
1 INSERT INTO users(name, limits) VALUES('小张','1,2,12'); 2 INSERT INTO users(name, limits) VALUES('小王','11,22,32');
Some fields in Mysql are of string type. How to find records that contain certain characters?
method one:
1 mysql> SELECT * FROM users WHERE limits like "%2%"; 2 +----+----+--------+ 3 | id |name| limits | 4 +----+----+--------+ 5|1|Xiao Zhang|1,2,12| 6 +----+----+--------+ 7|2|Xiao Wang|11,22,32| 8 +----+----+--------+ 9 2 row in set
In this way, users who do not have permission '2' for the second piece of data are also found, which does not meet expectations. So I checked the manual and used the mysql string function find_in_set().
Method Two:
1 mysql> SELECT * FROM users WHERE find_in_set('2', limits); 2 +----+----+--------+ 3 | id |name| limits | 4 +----+----+--------+ 5|1|Xiao Zhang|1,2,12| 6 +----+----+--------+ 7 1 row in set
This will achieve the effect we expect, and the problem will be solved!
Note: The mysql string function find_in_set(str1, str2) returns the position index of str1 in str2, and str2 must be separated by ",".
It cannot be used directly in hql, but we can use it like this:
from User u where find_in_set('2', limits)>0 ;
That is, '>0' must be included, otherwise an error will be reported.