问题描述
比如如下的SQL语句:select sum(f1),f2 from (select a.a1 as f1, a.a2 as f2, a.a3 as f3 from aleft join select b.b1 as f1,b.b2 as f2, b.b3 as f3 from bunion all select c.c1 as f1,c.c2 as f2, c.c3 as f3 from c where c.c1 < 100) group by f2要程序实现给查询语句添加条件 a.a1 > 10、b.b2 = 5 、c.c1 < 100达到下面的效果:select sum(f1),f2 from (select a.a1 as f1, a.a2 as f2, a.a3 as f3 from aleft join select b.b1 as f1,b.b2 as f2, b.b3 as f3 from bwhere a.a1 > 10 and b.b2 = 5union all select c.c1 as f1,c.c2 as f2, c.c3 as f3 from c where c.c1 < 100) group by f2怎么实现这样的效果请指点一下。
解决方案
已有的SQL文如果可以作为一个String取到的话,那就好办了。按照你自己写出来的那样,把那个String断开,在union all的前面插入你想要的条件。再把这个修改过的SQL文执行下就好了。如果不能取到的话,那基本就没戏了。除非让那条SQL文事先埋下用于扩展的参数。比如类似下面...left join select b.b1 as f1,b.b2 as f2, b.b3 as f3 from b #{将来可能要添加的条件参数}union all ...
解决方案二:
就是一个SQL语句的动态拼装么。根据传进来的条件,动态生成SQL语句。只要搞清楚哪些是不变的,哪些是变得。自然就写出来了。