MySQL 用户定义函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18618804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:44:43  来源:igfitidea点击:

MySQL user defined functions

mysqluser-defined-functions

提问by B.Mr.W.

I have a table contains a few columns say: column_1, column_2 and column_3.

我有一个包含几列的表,比如:column_1、column_2 和 column_3。

I appended an new column to the table called score. What I want to do is calculate the score based on these three columns and tune the parameters easily.

我在名为 score 的表中添加了一个新列。我想要做的是根据这三列计算分数并轻松调整参数。

Say my score formula looks like below:

假设我的分数公式如下所示:

score = a * column_1 + b * column_2 + c * column_3

is it possible to create a udf or process(never used before) to easily do that?

是否可以创建一个 udf 或进程(以前从未使用过)来轻松做到这一点?

so I have a function like getScore(a,b,c) and I could do something like:

所以我有一个像 getScore(a,b,c) 这样的函数,我可以做这样的事情:

select 
    column_1,
    column_2, 
    column_3, 
    getScore(0.5, 0.1, 0.4) as score
from table

or

或者

update table set score = getScore(0.5, 0.1, 0.4)

Thanks!

谢谢!

回答by Niko Hujanen

Yes.

是的。

CREATE FUNCTION `getScore`(`a` DECIMAL(12,4), `b` DECIMAL(12,4), `c` DECIMAL(12,4)) RETURNS DECIMAL(12,4)
BEGIN
    RETURN a + b + c;
END

SELECT getScore(0.3, 0.4, 0.5)
-> 1.2000

But if you need some values from the table, you need to include those as parameters too.

但是,如果您需要表中的某些值,则还需要将这些值作为参数包含在内。

SELECT getScore(column1, column2, column3, 0.5, 0.1, 0.4) AS score FROM table