具有来自不同表的多个Select语句的MySQL存储过程

时间:2013-12-01 22:20:57

标签: mysql stored-procedures

我正在尝试从mysql存储过程中的不同表中进行多次选择,如下所示

DELIMITER //  
CREATE PROCEDURE `NovemberSummary`(IN `branch` VARCHAR(60), IN `year` INT) NOT 
DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER 
BEGIN
select sum(sales.amount) as Sales from sales where month (sales.date)= 11 and 
sales.branch = branch;
select sum(expenses.amount) as Expenses from expenses where month(expenses.date)= 11
and expenses.branch = branch;
END

但它仅返回第一个Select,因为In result set仅包含Sales Column。

MySQL版本是5.6.11 - MySQL社区服务器

4 个答案:

答案 0 :(得分:4)

尝试这种方法:

DELIMITER //  
CREATE PROCEDURE `NovemberSummary`(IN `branch` VARCHAR(60), IN `year` INT) NOT 
DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER 
BEGIN
SELECT 
   ( select sum(sales.amount) from sales 
     where month (sales.date)= 11 and sales.branch = branch ) as Sales ,
   ( select sum(expenses.amount) from expenses 
     where month(expenses.date)= 11 and expenses.branch = branch ) as Expenses 
   ;
END

此过程返回仅包含两列的结果集:Sales + Expenses:

+-------+----------+
| Sales | Expenses |
+-------+----------+
|    20 |       15 |
+-------+----------+

,而不是只有一列的两个结果集。

+-------+
| Sales |
+-------+
|    20 |
+-------+

+----------+
| Expenses |
+----------+
|       15 |
+----------+

答案 1 :(得分:2)

CREATE PROCEDURE get_data ()
BEGIN
  SELECT Code, Name, Population, Continent FROM Country
    WHERE Continent = 'Oceania' AND Population < 10000;
  SELECT Code, Name, Population, Continent FROM Country
    WHERE Continent = 'Europe' AND Population < 10000;
  SELECT Code, Name, Population, Continent FROM Country
    WHERE Continent = 'North America' AND Population < 10000;
END;

答案 2 :(得分:0)

尝试一下

CREATE PROCEDURE `NovemberSummary`(IN `branch` VARCHAR(60), IN `year` INT) NOT 

DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER 

BEGIN

DECLARE SalesAmount VARCHAR(255) DEFAULT 0;
DECLARE ExpensesAmount VARCHAR(255) DEFAULT 0;

SELECT SUM(sales.amount) AS Sales INTO SalesAmount FROM sales WHERE MONTH (sales.date)= 11 AND 

sales.branch = branch;

SELECT SUM(expenses.amount) AS Expenses INTO ExpensesAmount FROM expenses WHERE MONTH(expenses.date)= 11

AND expenses.branch = branch;

SELECT SalesAmount AS Sales, ExpensesAmount AS Expenses;

END

答案 3 :(得分:0)

在存储过程中使用多重选择语句

尝试以下查询。

    select distinct ProdSubCategory, NULL,NULL
from Table1
inner join Table2 on ID_FK= ID_PK
where Table2.Type=@chvType and Table1.ProdCategory=@chvProdSubCategory

UNION ALL

select NULL, Brand,NULL
from Table1
inner join Table2 on ID_FK= ID_PK
where Table2.Type=@chvType and Table1.ProdCategory=@chvProdSubCategory

UNION ALL
select NULL, Price,NULL
from Table1
inner join Table2 on ID_FK= ID_PK
where Table2.Type=@chvType and Table1.ProdCategory=@chvProdSubCategor