如何合并在过程中返回多列的多重查询?

时间:2017-02-15 12:01:20

标签: mysql procedure

我有两张桌子叫病人和事件

---------         ----------
| users |         | events |
---------         ----------
|user_id|         |event_id|
|team_id|  1 -n   |user_id | 
|  .... |         | ....   | 
---------         ----------

我想创建一个程序来返回用户名及其活动的名称

CREATE PROCEDURE getAll(user_id INT)
BEGIN
  DECLARE id_user INT;
  DECLARE done INT DEFAULT FALSE;
  DECLARE user CURSOR FOR SELECT user_id FROM users WHERE team_id = id_team;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN usuarios;
  update_loop: LOOP
    FETCH user INTO id_patient;

    IF done THEN
        LEAVE update_loop;
    END IF;

    SELECT name FROM users WHERE user_id = id_user;
    SELECT nameE FROM events WHERE user_id = id_user LIMIT 0,2;
  END LOOP;
END

我想列出名称,然后列出要发回JSON的事件名称。我能怎么做 ?临时表?

2 个答案:

答案 0 :(得分:1)

您不需要使用cursor,请尝试:

DELIMITER $$

DROP PROCEDURE IF EXISTS getAll $$
CREATE PROCEDURE getAll(user_id INT)
BEGIN


SELECT u.user_id,u.name,e.ename FROM users u
INNER JOIN events e ON e.user_id = u.id_user
WHERE u.id_user = user_id ;

 END $$

DELIMITER ;

按用户分组的解决方案事件:

DELIMITER $$

    DROP PROCEDURE IF EXISTS getAll $$
    CREATE PROCEDURE getAll(user_id INT)
    BEGIN


    SELECT user_id,u.name,GROUP_CONCAT(e.ename SEPARATOR ',')  FROM users u
    INNER JOIN events e ON e.user_id = u.id_user
    WHERE u.id_user = user_id 
    GROUP BY u.id_user;

     END $$

    DELIMITER ;

答案 1 :(得分:0)

您不需要Procedure。只需JOIN

SELECT users.name, events.Ename from users, events 
    WHERE users.user_id=events.user_id 
          AND users.user_id = 52823;

52823当然是user_id

但是可以将它放在一个程序中:

DELIMITER //
CREATE PROCEDURE getAll(in user_id INT)
BEGIN
    SELECT users.name, events.Ename from users, events 
        WHERE users.user_id=events.user_id 
              AND users.user_id = user_id;
END //
DELIMITER ;