为什么mysql给出错误“不允许从函数返回结果集”?

时间:2012-08-09 09:22:28

标签: mysql sql

我正在尝试使用phpMyAdmin创建一个MySQL函数并收到此错误。

#1415 - Not allowed to return a result set from a function

功能代码如下

DELIMITER $$

CREATE FUNCTION get_binary_count(a INT, c INT)
RETURNS INT
DETERMINISTIC 

BEGIN

DECLARE c1, c2 INT;
SET c1=0;
SET c2=0;

SELECT left_id AS c1 FROM mlm_user_mst WHERE parent_id=a AND left_id>0;
SELECT right_id AS c2 FROM mlm_user_mst WHERE parent_id=a AND right_id>0;

IF(c1>0 AND c2>0)
THEN
SET c=c+1;
SET c=c+get_binary_count(c1,0);
SET c=c+get_binary_count(c2,0);
END IF;

RETURN c;

END$$

DELIMITER ;

有什么建议吗?

提前致谢

2 个答案:

答案 0 :(得分:23)

因为

SELECT left_id AS c1 FROM mlm_user_mst WHERE parent_id=a AND left_id>0; 

不设置变量c1,它返回一个名为c1

的列的集合

你想要

SELECT left_id INTO c1 FROM mlm_user_mst WHERE parent_id=a AND left_id>0; 

同样适用于c2。

答案 1 :(得分:5)

这是因为您正在使用SELECT个查询,这些查询的输出未存储到变量中,或者临时存储在FUNCTION内的必须。函数只能返回一个值。所以你的代码应该是这样的:

CREATE TABLE t1 AS SELECT left_id AS c1 FROM mlm_user_mst WHERE parent_id=a AND left_id>0;
CREATE TABLE t2 AS SELECT right_id AS c2 FROM mlm_user_mst WHERE parent_id=a AND right_id>0;

SELECT left_id AS c1 INTO @c1 FROM mlm_user_mst WHERE parent_id=a AND left_id>0 LIMIT 1; 

SELECT right_id AS c2 INTO @c2 FROM mlm_user_mst WHERE parent_id=a AND right_id>0 LIMIT 1;