[英]MySQL Using stored procedure in select statement
我有一个这样的存储过程:
$connection->query('
drop procedure if exists listing_count;
create procedure listing_count(IN parent int(11))
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
(select count(*) from listing_category where category in(select id from ids));
end');
$fetch=$connection->query('select *,listing_count(id) as listing_count from category')->fetchall(pdo::FETCH_UNIQUE|pdo::FETCH_ASSOC);
我想像函数一样使用我的程序。 这样, listing_count
就可以得到计数,以便我可以使用它。 我需要创建一个单独的功能吗? 程序可以获取我的计数并返回吗?
将其转换为如下功能:
drop function if exists listing_count;
create function listing_count(parent int(11)) returns int(11) deterministic
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
return (select count(*) from listing_category where category in(select id from ids));
end
但这是行不通的。 我对过程与函数不是很熟悉,但是我认为我无法像在过程中那样将所有功能添加到函数中。
我想像函数一样使用我的程序。
您不能那样做™。
我建议您将sp转换为存储函数。 在任何情况下,这都是一个好主意,因为它返回一个值。 您现在所拥有的方式,它将返回一个单列单行结果集。 如果它是一项功能,它将很容易在您需要的每种情况下运行。 相比之下,返回结果集的存储过程几乎不那么容易使用。 例如,参见此。 如何使用存储的MYSQL过程中的表输出
或者,您可以编写一个存储函数来包装存储过程并返回值。 我认为这是次等的解决方案,因为它具有额外的复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.