查到的结果的某个字段在一串字符串之中
以下内容为转载
重点在于字符串的形式,'kirito,asuna,taki,mitsuha',这种形式在mysql,没有可以直接用的,改变形式即可
创表:
create table student(
id bigint(20) not null,
name varchar(20),
course varchar(20),
grade int(10),
primary key(id)
);
插入数据:
insert into student(id,name,course,grade) values(1,'taki','sword',60);
insert into student(id,name,course,grade) values(2,'mitsuha','sword',50);
insert into student(id,name,course,grade) values(3,'kirito','sword',95);
insert into student(id,name,course,grade) values(4,'asuna','sword',90);
insert into student(id,name,course,grade) values(5,'taki','magic',50);
insert into student(id,name,course,grade) values(6,'mitsuha','magic',60);
insert into student(id,name,course,grade) values(7,'kirito','magic',60);
insert into student(id,name,course,grade) values(8,'asuna','magic',95);
查询:
select * from student where course = 'sword' and name REGEXP replace('kirito,asuna',',','|');
通过replace方法把字符串中的逗号换成 | 号,然后通过recexp 'kirito|asuna'来使结果在这段字符串中
先用java转:
public class Test {
public static void main(String[] args){
String string = "kirito,asuna,taki,mitsuha";
System.out.println(string);
System.out.println(string.replace(",","|"));
}
}
也可以先用java弄成可以mysql中可以直接in的形式,如
public class Test {
public static void main(String[] args){
String string = "kirito,asuna,taki,mitsuha";
System.out.println(string);
System.out.println("('"+String.join("','",string.split(","))+"')");
}
}
直接就可以查询