【问题标题】:How to use sql IN clause with sql LIKE如何在 sql LIKE 中使用 sql IN 子句
【发布时间】:2019-04-29 23:34:26
【问题描述】:

我有 spring boot 应用程序,在其中一个 DAO 类中,我们有一种方法来检索一些数据,因为我们正在使用下面的查询,这里使用namedParameterJdbcTemplate

select student_id from student_records where create_date >= timestamp '"+appProps.getFromDate()+"' and  create_date <= timestamp '"+appProps.getToDate()+"' and student_id in (:studentIdList)

完整的方法如下所示

public List<String> readMatchingStudentIds_ALL(List<String> inputStudentIdsList){
            List<String> macthingStudentIdsList = new ArrayList<>();
            try{
                Map<String, List<String>> namedParameters = Collections.singletonMap("studentIdsList", inputStudentIdsList);
                String query = " select student_id from student_records where create_date >= timestamp '"+appProps.getFromDate()+"' and  create_date <= timestamp '"+appProps.getToDate()+"' and student_id in (:studentIdList)";

                macthingStudentIdsList =  namedParameterJdbcTemplate.queryForList(query, namedParameters, String.class);
            }catch(Exception e)
            {
                throw new RuntimeException(e.getMessage(),e);
            }
            return macthingStudentIdsList;
     }

一切正常,但现在问题来了,例如传入的学生列表包含“AFE1245”但在我们的数据库中我们有如下数据“000AEF1245”,我的意思是 0 是前缀,我们不知道有多少个 0有前缀,对于单个查询,我们可以使用 LIKE 运算符,如下所示

select student_id from student_records where student_id like '%input_student_id'

但我的情况不同,因为我们需要使用 sql IN 子句,他们是否有可能我们可以同时使用 sql IN 子句和 LIKE 或者是他们的任何其他方式

【问题讨论】:

  • col1 IN(1,2,3 ) 只是 ( col1=1 or col1=2 or col1=3 ) 的缩写形式,您不能将这些相等测试转换为 LIKE
  • @Used_By_Already 是的,您可以:col like any(array[pat1, pat2, pat3])。真正的问题是student_id like any(array[:studentIdList])) 中的:studentIdList 是否会得到妥善处理。
  • any(arrayin ( ...) 对后者提出的问题不同。您已将其替换为不同的功能。关于 in() 的使用,我上面的评论仍然正确
  • @Used_By_Already 你误会了。 col in (a, b, c) 等价于col = any(array[a, b, c])(PostgreSQL 甚至将in 转换为any(array[]))所以col like any(array[pat1, pat2, pat3])in (list) 的LIKE 形式。
  • @muistooshort IN ANY 您已替换第一个为第二个。甚至 IN 上的文档也声明 “这是 expression = value1 OR expression = value2 OR ... 的简写符号” 试试这个:rextester.com/DUZZ23268

标签: sql postgresql spring-boot spring-jdbc


【解决方案1】:

您可以通过单独的 LIKE 和 OR 来做到这一点:

SELECT student_id FROM student_records
WHERE student_id LIKE '%input_student_id'
OR  student_id LIKE 'input_student_id%'
OR  student_id LIKE '%input_student_id%';

参考this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2011-08-16
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2021-08-10
    相关资源
    最近更新 更多