簡體   English   中英

MySQL在select語句中使用存儲過程

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM