16

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

#1415 - 不允许从函数返回结果集

功能代码如下:

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 ;

有什么建议么?

提前致谢。

4

2 回答 2

42

因为

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 也是如此。

于 2012-08-09T09:24:13.080 回答
7

那是因为您正在使用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;
于 2012-08-09T09:24:25.077 回答