使用已在存储过程中的另一个SELECT中返回SELECT

时间:2015-12-09 10:15:04

标签: mysql sql stored-procedures

我有一个返回两个结果集的存储过程。但第二个SELECT首先是通过连接相关的。

MySQL有没有办法摆脱重复?我怎么能解决已经完成的SELECT?它会提高性能吗?

CREATE PROCEDURE `procedure`()
BEGIN
    SELECT * FROM users WHERE age > 20;
    SELECT item_id FROM items INNER JOIN (SELECT * FROM users WHERE age > 20) ON user_id;
END 

1 个答案:

答案 0 :(得分:1)

create table items
(
    item_id int auto_increment primary key,
    user_id int not null
    -- FK not shown
);

create table users
(
    user_id int auto_increment primary key,
    age int not null
);

insert items(user_id) values (1),(1),(2);
insert users (age) values (22),(1);

目前的数据

select * from items;
+---------+---------+
| item_id | user_id |
+---------+---------+
|       1 |       1 |
|       2 |       1 |
|       3 |       2 |
+---------+---------+
select * from users;
+---------+-----+
| user_id | age |
+---------+-----+
|       1 |  22 |
|       2 |   1 |
+---------+-----+

查询

SELECT item_id FROM items 
join
(   select user_id
    from users
    where age>20
) xDerived
on xDerived.user_id=items.user_id;

+---------+
| item_id |
+---------+
|       1 |
|       2 |
+---------+

那么,那是你的查询。一个查询,1个结果集。

临时表的描述

这是基于上述操作问题的临时表的视图(不在下面)。

drop procedure if exists proc123;
delimiter $$
create procedure proc123 (iParam int)
begin
    insert myTempThing (theI,theWhen) select iParam,now();
end
$$
delimiter ;

-- the following is a temp table NOT created inside a stored proc
-- as in, via whatever programming language you are using
-- will incur time overhead especially if indexes are used, but regardless
create temporary table myTempThing
(   id int auto_increment primary key,
    theI int not null,
    theWhen datetime not null
);

insert myTempThing (theI,theWhen) select 123,now();
-- now wait a bit and run the call stmt below

-- again I am still at a workbench prompt

call proc123(456);

select * from myTempThing;
-- two rows