接口传多字段查询方法介绍
1.案例
抽奖明细记录查询,需要查询draw_record表,通过user_id、pool_code关键字段查询,需要传递多个code值(card_1,card_2),获取包含这些code值的记录。
2.总体思路
前端传递参数poolCode数组保存多个code值,参数传递转化为逗号分割的字符串,传递到接口,接口直接使用该字段通过mysql内置的查询方法,如in pool_code、find_in_set(pool_code, ‘’)查询。
个人觉得接口传递对象然后解析的方式不如直接传递字符串简便,且不容易出现转化方面的错误,有更好的方法欢迎留言。
3.编写方法
var poolCodes = new Array('card_1','card_2');
var jsonStr = poolCodes.toString();
$.ajax({
url:"xxx",
type:'get',
dataType:'json',
data:{
userId:"xxx",
poolCode:jsonStr,
},
...
})
方法一:使用in查询
@Query(value = "select * from draw_record where user_id = :userId and pool_code in :poolCode")
public List<Object> findByCodes(@Param("userId") String userId, @Param("poolCode") String poolCode);
方法二:使用find_in_set查询
@Query(value = "select * from draw_record where user_id = :userId and find_in_set(pool_code, :poolCode)")
public List<Object> findByCodes(@Param("userId") String userId, @Param("poolCode") String poolCode);