通过不重复数学来优化 sql 查询
这是 Oracle 中的查询,我试图从中删除多余的数学运算:
SELECT name,
CASE
when nvl(num1,0) + nvl(num2,0) - nvl(num3,0) > 0
THEN nvl(num1,0) + nvl(num2,0) - nvl(num3,0)
ELSE 0
END
as result,
.... from ....
How do I not重复上面的求和?
“结果”应包含上述表达式的 - 值 if > 0
- 0 if the value of expression is <= 0.
Here is the query in Oracle I was trying to remove the redundant math operation from:
SELECT name,
CASE
when nvl(num1,0) + nvl(num2,0) - nvl(num3,0) > 0
THEN nvl(num1,0) + nvl(num2,0) - nvl(num3,0)
ELSE 0
END
as result,
.... from ....
How do I not repeat the summation above?
The 'result' should contain - value of the above expression if > 0
- 0 if the value of expression is <= 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,您可以将 CASE 表达式替换为:
OrbMan 的答案通常更有用。
In this case you could replace your CASE expression with:
OrbMan's answer is more generally useful though.
使用派生表:
Use a derived table:
假设您出于性能原因想要摆脱数学计算,那么最好的方法(从 DBA 的角度来看)是创建另一个名为
result
的列,然后使用插入/更新触发器当行更改时,使用您想要的值自动填充它:这样,仅在需要时(在行创建/更改时)而不是在每次读取时进行计算。这可以分摊读取次数多于写入次数的数据库的操作成本(根据我的经验,这接近所有数据库)。
然后,您的查询变得简单且快得令人眼花缭乱:
此方法之所以有效,是因为:
当然,这一切都是假设 Oracle 有触发器。我自己就是一名 DB2 人员,但如果 Oracle 如此愚蠢以至于没有它们,我会感到惊讶。话又说回来,据我所知,也许 Oracle仍然无法区分 NULL 和空字符串,所以谁知道呢? :-)
Assuming you want to get rid of the math for performance reasons, the best way to do this (from a DBA's point of view) is to create another column called
result
, then use an insert/update trigger to automatically populate it when a row changes, with the value you want:That way, the calculation is only done when required (on a row create/change) rather than on every single read. This amortises the cost of the operation on databases that are read more often than written (which, in my experience, is close to all of them).
Then your query becomes a simple and blindingly fast:
This method works because:
This is all assuming Oracle has triggers of course. I'm a DB2 man myself but I'd be surprised if Oracle was so brain dead it didn't have them. Then again, for all I know, maybe Oracle still can't distinguish between NULL and an empty string, so who knows? :-)