开发者

mysql calculation field stored in another field

I have fields in mysql that look like this:

constant1 , constant2, variable1, variable2, formula

The formula field stores a formula utilizing constant1, constant2, variable1 and variable2.

For example开发者_开发百科, the formula field may contain a calculation like this:

constant1 * variable1

When I use a select statement like this:

SELECT constant1, constant2, variable1, variable2, formula
FROM table

How do I retrieve the calculation result of constant1 * variable1 based on formula field?


You need one of two approaches:

  • Call some sort of eval function on your formula.
  • Parse the formula into an expression tree, substitute the values and then evaluate the expression.

Usig eval is quick to implement but dangerous because it could do something you didn't expect. Parsing the formula is best done with a dedicated library for building parsers, but if your expression syntax is very simple you could write a parser yourself without using a library. In either case SQL isn't the right language for this.

I'd recommend finding a library that can help you parse the formula. Whichever route you choose though, I'd suggest doing the bulk of the work on the database client, not in SQL. SQL was simply not designed for this sort of task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜