近期的一个需求,查询数据类型
通常做法是 定义b字段为varchar 存入类型:(1,2,4),在查找时,使用 like "%1%";
这种查询会存在问题,当类型有 10,11等等,则会 like 不出正确的数据.
当超出的话,可以试试使用下面的方法
数据库字段保存为十进制转二讲制再求和的sql查询
例:
a字段type_bit值为10 (其实是2,4 通过 十进制转二讲制再求和计算得出的)
1.当需要查询出类型同时匹配单个2或者单个4或者单个(4,2)时
select * from table where type_bit & getBitSum("4,2") = getBitSum("4")
2.当需要查询出包含类型是2或者4或者4,2时
select * from table where type_bit & getBitSum("4") > 0
3.当需要查询出不包含类型是2或者4或者(4,2)时
select * from table where type_bit & getBitSum("2") = 0
4.当需要查询出包含类型是2,4并且不包含(1,3)时
select * from table where (type_bit & getBitSum("2,4") > 0 and type_bit & getBitSum("1,3") = 0)
备注:
getBitSum()是java方法,通过计算后,把值放到sql中查询
public static Long getBitSum(string numberStr) {
String[] numberArr = numberStr.split(",");
List<String> numberList = Arrays.asList(numberArr);
List<Long> collect = numberList.stream().map(Long::parseLong).collect(Collectors.tolist());
//一行代码
//List<Long> collect = Arrays.stream(numberStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
Long num = 0L;
for(long i : collect) {
double pow = Math.pow(2,i - 1);
num += (long)pow;
}
return num;
}