如何使用java正则表达式将查询列表sql转换为查询计数sql

时间:2015-03-17 12:23:17

标签: java sql regex

我想删除sql中的order by,并转换

select a,b,c from进入select count(*) from

<小时/> select uid, uname from user order by uid

=&GT;

select count(*) from user

<小时/> select uid, (select depname from department t01 where t02.depid = t01.depid ) from user t02 order by uid

=&GT;

select count(*) from user t02

<小时/> select uid, '('||uname||')' from user

=&GT;

select count(*) from user

<小时/> select uid from (select uid,rownum as row_num from user order by uid) where row_num < 10 order by uname

=&GT;

select count(*) from (select uid,rownum as row_num from user order by uid) where row_num < 10

<小时/> 如何使用java正则表达式做到这一点?

select uid, uname from user order by
hibernate可以自动将其转换为页面查询select uid, uname from user order by limit xxxx,执行它我们可以得到一个列表。

然后如果我们执行select count(*) from user,我们将获得用户数。

pageNopageSize由我自己设定,pageNumrecord_count/pageSize。我希望通过一个sql获取table/grid的所有数据,但我不知道如何将查询列表sql转换为查询计数sql。

1 个答案:

答案 0 :(得分:1)

假设order by结尾,你可以使用

query = query
 .replaceFirst("(?is)\\sorder\\s+by\\s.*$","");
 .replaceFirst("(?is)^\\s*select\\s.*?from\\s","select count(*) from ");

但是,它并不合适。分析SQL查询需要语法分析,这超出了正则表达式的范围。我给出的例子将失败

select ... from ... where title = 'I want to order by my cat'

这是一个简单的反例,但你可以想象很多更复杂的SQL查询。