raj*_*air 3 sql database optimization design-patterns union-all
我试图找出以下是一个记录良好的模式(或反模式),以减少应用程序延迟.我已经尝试过这种技术,但从表面上看这似乎可以节省20%的延迟.我想知道是否有任何副作用,我应该知道
语境:
你有一个方法/函数/过程,它对数据库进行多次SELECT调用,你需要优化它.
让我们说你的方法的流程是:
getDBConnection()
execute("Select a,b from tableA");
bind a with varA
bind b with varB
---SOME Business Logic-----
execute("Select c,d from tableB");
bind c with varC
bind d with varD
---SOME more Business Logic-----
execute("Select e,f from tableC");
bind e with varE
bind f with varF
---SOME more Business Logic-----
releaseConnection()
Run Code Online (Sandbox Code Playgroud)
解决方案:使用Union ALL对数据库进行一次调用
getDBConnection()
execute("Select a,b,'sqlA' from tableA"+
" UNION ALL "+
" Select c,d,'sqlB' from tableB"+
" UNION ALL "+
"Select e,f,'sqlC' from tableC");
bind a,b where records have "sqlA"
bind c,d where records have "sqlB"
bind e,f where records have "sqlC"
releaseConnection()
--------Do all Business Logic here-----
Run Code Online (Sandbox Code Playgroud)
使用union限制了查询的"形状".它们基本上必须以相同的顺序返回相同数量和(兼容)类型的列.
更好的方法是在单个命令中使用多个查询,然后处理多个结果集:
execute("Select a,b from tableA;"+
"Select c,d from tableB;"+
"Select e,f from tableC");
Run Code Online (Sandbox Code Playgroud)
或者可以创建一个运行这些查询的专用存储过程.
除此之外,这种优化技术可以将不相关的操作混为一谈,这将限制以后各个操作的可重用性.您可能想要考虑一种更好地分离这些操作的设计,并使用某种方式QueryManager首先收集它们,然后将它们一起运行.