简体   繁体   中英

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. I have a simple SQL like this:

-- 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:

-- 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:

-- 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. However, I don't know how to use this result like in second 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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