简体   繁体   English

MySQL:在SELECT和FROM中使用存储过程

[英]MySQL : Use Stored Procedure in SELECT and FROM

I have a question related to stored procedure. 我有一个与存储过程有关的问题。 I have a table called as account with a field named agent. 我有一个名为account的表,其中有一个名为agent的字段。 I have a simple SQL like this: 我有一个像这样的简单SQL:

-- First SQL --
SELECT      account.agent
FROM        account
GROUP BY    account.agent
HAVING      account.agent > 0

If I insert this above SQL to a table called as agent_structure, I simply can JOIN this table with another table (eg customer) by using SQL like this: 如果将上面的SQL插入到称为agent_structure的表中,则可以使用SQL像下面这样简单地将这个表与另一个表(例如客户)联接:

-- Second SQL --
SELECT      agent_structure.agent,
            customer.name, 
            customer.age, 
            customer.country
FROM        agent_structure
INNER JOIN  customer ON agent_structure.agent = customer.id

The problem is, I don't want to add another table only for saving one field. 问题是,我不想仅为了保存一个字段而添加另一个表。 So, I try to use stored procedure. 因此,我尝试使用存储过程。 So, I put the first SQL to procedure like this: 因此,我将第一个SQL放入这样的过程中:

-- FIRST SQL put into Procedure --
CREATE PROCEDURE agent_structure() 
SELECT      account.agent
FROM        account
GROUP BY    account.agent
HAVING      account.agent > 0

This looks very well, since when I write 'CALL agent_structure();', the SQL output the single field that I want. 这看起来非常好,因为当我编写“ CALL agent_structure();”时,SQL输出所需的单个字段。 However, I don't know how to use this result like in second SQL. 但是,我不知道如何像在第二个SQL中那样使用此结果。 I try this dummy way after give out parameter to the procedure, but it doesn't work: 在给程序分配参数后,我尝试使用这种虚拟方法,但是它不起作用:

-- Second SQL but use stored procedure --
CALL agent_structure(@a);
SELECT      @a,
            customer.name, 
            customer.age, 
            customer.country
FROM        @a
INNER JOIN  customer ON @a.agent = customer.id

The goal is like using a script to another script. 目标就像将一个脚本用于另一个脚本。 I don't want to put the first script directly to the second one since my actual script is larger and have multiple layers. 我不想将第一个脚本直接放到第二个脚本中,因为我的实际脚本较大且具有多层。 Anyone can help me give the solution for this? 有人可以帮我解决这个问题吗?

As I can see you can't include Stored Procedure inside SELECT. 如我所见,您不能在SELECT内包含存储过程。 In this case you need to use View instead Stored Procedure. 在这种情况下,您需要使用“查看”而不是“存储过程”。

CREATE VIEW agent_structure AS
    SELECT      account.agent
    FROM        account
    GROUP BY    account.agent
    HAVING      account.agent > 0
SELECT      customer.name, 
                customer.age, 
                customer.country
    FROM        agent_structure AS a
    INNER JOIN  customer AS c ON a.agent = c.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM