【发布时间】:2018-02-08 00:30:20
【问题描述】:
SQL 查询有时会变得难以处理。所以我有一个包含多个 OR 操作和 REGEX 的 SQL 查询。而通过 JAVA 代码运行的时间在庞大的数据条目上超过了预期的时间。
下面是查询:
SELECT * FROM tableName WHERE (col1 REGEXP ('xyz'|'abc') OR (col2 = 15 AND (col1 REGEXP ('xyz'|'abc')))) AND col3>='2017-08-28' AND col3<='2017-08-30';
休眠代码:
public List<MyModel> getAllMatchedEntries() {
long lStartTime = new Date().getTime();
Query query = ((SQLQuery) getSession().createSQLQuery( "SELECT * FROM tableName WHERE (col1 REGEXP :list OR (col2 = 15 AND (col1 REGEXP :list))) AND col3>=:sd AND col3<=:ed"). setResultTransformer(Transformers.aliasToBean(LeadGenViewTable.class)).setParameter("list", regexlist).setParameter("mid", merchant_id).setParameter("todayDate", sd).setParameter("ed", ed));
List<MyModel> list = query.list();
long lEndTime = new Date().getTime();
long output = lEndTime - lStartTime;
list= list.stream().filter(distinctByKey(t -> t.getSomeCol())).collect(Collectors.toList());
System.out.println("Time Taken "+output);
return list;
}
出人意料地在日志中输出:
Time Taken 45616
由于 REGEXP / OR 操作,我很难弄清楚发生的时间延迟。帮助将不胜感激。
【问题讨论】:
-
运行
EXPLAIN,它可能会为查询完成的数据过滤提供一些输入。您也可以尝试将BETWEEN用于col3条件。 -
您是如何计算预期时间的?您是否直接对数据库运行完全相同的查询?如果你使用 hibernate,你永远不必编写一个普通的 sql 查询
-
@XtremeBaumer 请检查更新的问题。是的,运行相同的查询会在 2 秒内对相同的数据给出结果。编写普通 sql 查询的原因是正则表达式,因为我找不到使用条件或 hql 实现正则表达式的最佳方法。
-
@AnkitaGoyal this is a solution 这可能有效。 another example 或者你扩展你的方言像this