test1 是对传递两个变量 v_col1 和 v_col2 后创建的表的行进行计数的过程。当我在 MySQL 上运行它时,它显示
“MySQL 返回了一个空结果集(即零行)。(查询花费了 0.0020 秒)”
但是我无法从 php.ini 调用它。
Delimiter $$
create procedure test1()
BEGIN
BLOCK1: begin
declare v_col1 int(10);
declare no_more_rows1 boolean default FALSE;
declare cursor1 cursor for
select content_id
from topic_list where topic_id=1;
declare continue handler for not found
set no_more_rows1 = TRUE;
open cursor1;
LOOP1: loop
fetch cursor1
into v_col1;
if no_more_rows1 then
close cursor1;
leave LOOP1;
end if;
BLOCK2: begin
declare v_col2 int(10);
declare no_more_rows2 boolean default FALSE;
declare cursor2 cursor for
select content_id
from content_upvotes
where u_id_upvoter = 1;
declare continue handler for not found
set no_more_rows2 = TRUE;
open cursor2;
LOOP2: loop
fetch cursor2
into v_col2;
if no_more_rows2 then
close cursor2;
leave LOOP2;
end if;
select count(*) as mynum from (SELECT *from content_upvotes where content_id=v_col1) t1 join (select u_id_upvoter as user_id from content_upvotes where content_id= v_col2) t2 on t1.u_id_upvoter=t2.user_id ;
end loop LOOP2;
end BLOCK2;
end loop LOOP1;
end BLOCK1;
end $$
DELIMITER ;
请帮帮我。
最佳答案
首先,观察结果(这不是您提出的问题的答案)...
对于它应该完成的任务来说,这个过程似乎过于复杂。
<小时/>问:这个过程会计算行数吗?
答:如果您询问此过程是否会返回“行数”...
它将有条件地执行,条件是 cursor1
返回至少一行,并且 cursor2
在过程执行期间的某个时刻返回至少一行。回答你的第一个问题...
是的,mynum
(过程的输出参数)可能会填充“行数”。
返回的“计数”将来自select count(*)
查询的最后执行(位于loop2的底部)。任何先前执行 select count(*)
查询的结果都将被丢弃。
如果 cursor1
不返回行,则答案为否,该过程不会返回任何“行数”。此外,如果 cursor2
从未返回一行,那么答案也是否。
问:如何从 PHP 调用此过程?
答:假设您正在使用 PDO,则可以使用如下模式:
<?php
$sth = $dbh->prepare("CALL test1(?)");
$sth->bindParam(1, $return_val, PDO::PARAM_INT, 20);
$sth->execute();
print "call to msyql stored procedure test1 returned $return_val\n";
?>
<小时/>
为了跟进我最初的观察...我对这个程序存在的任何充分理由感到困惑。
<小时/>跟进
上面的代码示例解决了具有 OUT
参数的原始过程定义。问题中的过程定义已更改为删除 OUT
参数,并且 SELECT ... INTO var
SQL 语句已更改为删除 INTO var
。修改后的过程有可能返回零个、一个或多个结果集。
要执行过程(不带参数)并从过程中检索所有结果集,您可以使用如下模式:
<?php
$sth = $dbh->prepare("CALL test1()");
$sth->execute();
$results = array();
do {
$rowset = $sth->fetchAll();
if($rowset) {
$results [] = $rowset;
}
} while ($sth->nextRowset());
?>
关于php - 这个过程会计算行数吗?我如何从 php 调用这个过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816018/