【问题标题】:Mysql query with In clause regex带有 In 子句正则表达式的 Mysql 查询
【发布时间】:2016-11-08 08:48:29
【问题描述】:

我有一个这样的 SQL 查询:

"select f.filterid as filtename, f.id as filtertext " +
    "from filter f " + 
    "where group_Id = '" + id +"' " + 
    "OR groupIds like '%." + id + ".%' ";

我想将一个 id 列表传递给该查询以提高性能。我不知道 REGEX 是否适用于 IN 子句。我尝试了下面的一个,它不起作用,不知道在 REGEX 的情况下使用什么。

"select f.filterid as filtename, f.id as filtertext from filter f " + 
    "where group_Id in ("+StringUtils.join(ids, "','")+")" + 
    "OR groupIds in ("+StringUtils.join(ids, "','")+")"";

谢谢。

【问题讨论】:

  • group_Id 是 varchar 数据类型的数值数据类型?
  • group_Id 是 int 而 groupIds 是 varchar

标签: java mysql sql


【解决方案1】:

我建议使用Query#setParameter 来实现这一点,如果您使用的是 JPA,您可以轻松地在 setParameter 中提供您的 ids 列表。

但对于您当前的分辨率,您可以尝试以下更改。

不确定您的 group_Id 列是否需要整数或字符串数​​据类型,我会针对这两种情况提出更改建议。

如果它需要字符串 - 您缺少开头的“ ' ”,如下更改您的代码

如果它需要整数类型 - 你不应该用“'”包裹你的逗号分隔符,删除它们如下

"select f.filterid as filtename, f.id as filtertext from filter f " + "where group_Id in ("+StringUtils.join(ids, ",")+")" + "OR groupIds in ("+"'"+StringUtils.join(ids, "','")+"'"+")";

尝试运行此查询并查看是否获得所需的结果集

【讨论】:

  • 我需要为 groupIds 传递正则表达式字符串列表,我无法在普通的 sql 选择查询中做到这一点。
  • 你的正则表达式字符串是什么样子的?
  • 它看起来像 1.12345.2,我只对 %.12345.% 值列表感兴趣。在这里看到这篇文章。 stackoverflow.com/questions/9540087/…
  • 您不能在 MySQL DB 中将 LIKE 与 IN 子句一起使用,您可以选择为 groupIds 列表中的元素数量重复 LIKE 子句
  • 如果我有一个一百万的列表,那么查询看起来很糟糕。
【解决方案2】:

或许问题出在StringUtils.join方法的使用上。 您可以像下面的代码一样编辑您的 sql。

 select f.filterid as filtename, f.id as filtertext from filter f where group_Id in ('groupA_id', 'groupB_id', 'groupC_id') 

如果你的ids 是{"groupA_id", "groupB_id", "groupC_id"},那么

"select f.filterid as filtename, f.id as filtertext from filter f where group_Id in (" + "'" + StringUtils.join(ids, "','") + "'" +")"

【讨论】:

    【解决方案3】:

    试试这样的:

    Query query = session.Query("select f.filterid as filtename, f.id as filtertext from filter f where group_Id in :list");
    query.SetParameterList(":list", ListOfIds);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多