mysql存储过程中的多个select语句

时间:2016-12-07 12:20:12

标签: mysql stored-procedures

我正在学习编写存储过程。我想在我的mysql存储过程中有三个select语句。 第二个和第三个select语句需要其上部select语句的结果。 我试着写如下。但没有成功。

CREATE DEFINER=`root`@`localhost` PROCEDURE `SPTeam`(IN date_x date, OUT   emplist3 varchar(200))

BEGIN
SELECT
(
   select emp_event.employee_id as emplist1
   from emp_event
   where emp_event.date = date_x
), 
(
   select emp_position.employee_id as emplist2
   from emp_position
   where FIND_IN_SET(emp_position.employee_id, emplist1)=0
   AND emp_position.position = "Cameraman"
),
(
   select employee.name as emplist3
   from employee
   where employee.id IN (emplist2)
);
END

这是我得到的错误。

Error Code: 1054. Unknown column 'emplist1' in 'where clause'   

有人请指正。 谢谢你。

2 个答案:

答案 0 :(得分:0)

您可以将每个选择结果存储在变量中,然后对这些变量进行选择:

DECLARE @emp_event as int
DECLARE @emp_position as int
DECLARE @emp_employeeName as int

SET @emp_event = (select emp_event.employee_id from emp_event where emp_event.date = date_x)
SET @emp_position = (select emp_position.employee_id from emp_position where FIND_IN_SET(emp_position.employee_id, @emp_event)=0 AND emp_position.position = "Cameraman")
SET @emp_employeeName = (select employee.name from employee where employee.id IN (@emp_position))

SELECT @emp_event as emplist1, @emp_position as emplist2, @emp_employeeName as emplist3

答案 1 :(得分:0)

如果我正确地告诉你需要什么,那就是这样的:

   select employee.name as emplist3
   from employee
   where employee.id IN (
      select emp_position.employee_id
      from emp_position
      where emp_position.employee_id IN (
         select emp_event.employee_id
         from emp_event
         where emp_event.date = date_x
      )
      AND emp_position.position = "Cameraman"
   )