deterministic mysql_MySQL中的确定性函数

MySQL中的确定性函数是指对于相同的输入参数总是返回相同结果的函数。然而,如果函数内部包含如查询表的数据这样的行为,则可能因并发操作而变得非确定。尽管存在误解,MySQL不会检查声明为DETERMINISTIC的函数是否真的确定。错误声明可能会导致优化器选择错误的执行计划或性能下降。
摘要由CSDN通过智能技术生成

bd96500e110b49cbb3cd949968f18be7.png

I got confused with a seemingly simple concept. Mysql defines deterministic function as a function that

always produces the same result for the same input parameters

So in my understanding, functions like

CREATE FUNCTION foo (val INT) READS SQL DATA

BEGIN

DECLARE retval INT;

SET retval = (SELECT COUNT(*) FROM table_1 WHERE field_1 = val);

RETURN retval;

END;

are not deterministic (there is no guarantee that delete/update/insert does not happen between 2 calls to the function). At the same time, I saw many functions which do pretty much the same, i.e. return value based on result of queries, and declared as DETERMINISTIC. It looks like I'm missing something very basic.

Could anyone clarify this issue?

Thanks.

Update

Thanks for those who answered(+1); so far it looks like there is a widespread misuse of DETERMINISTIC keyword. It is still hard to believe for me that so many people do it, so I'll wait a bit for other answers.

解决方案

From the MySQL 5.0 Reference:

Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used. Prior to MySQL 5.0.44, the DETERMINISTIC characteristic is accepted, but not used by the optimizer.

So there you have it, you can tag a stored routine as DETERMINISTIC even if it is not, but it might lead to unexpected results or performance problems.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值