错误 - 由于GROUP BY,“结果由多行组成”

时间:2013-02-05 03:01:00

标签: mysql sql group-by

我有以下MYSQL存储过程,

CREATE PROCEDURE DWH.product_stats(OUT int_return INT)
BEGIN
  DECLARE vc_sku, 
      vc_prod_id    VARCHAR(100);

  DECLARE int_views,
      int_fav,
      int_month, 
      int_year, 
      not_found     INT DEFAULT 0;

 DECLARE cur_sku CURSOR FOR

 SELECT product_id, sku FROM product LIMIT 0,10;

 DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;

 OPEN cur_sku;
 REPEAT

FETCH cur_sku INTO vc_prod_id, vc_sku;
IF NOT not_found THEN
  -- Number of Views and Favs
  SELECT  COUNT(CASE WHEN event_type_id = 1 THEN 1 END) AS views,
          COUNT(CASE WHEN event_type_id = 5 THEN 1 END) AS favs,
          MONTH(logged_at) AS log_mon, 
          YEAR(logged_at) AS log_year INTO int_views, int_fav, int_month, int_year
  FROM report_event
  WHERE object_id = vc_prod_id
  GROUP BY log_mon, log_year
  ORDER BY log_year, log_mon; 

  -- DEBUG
  SELECT vc_sku, vc_prod_id, int_views, int_fav, int_month, int_year ;
END IF;
UNTIL not_found END REPEAT ;
CLOSE cur_sku;

END;

如果我正常运行,则没有错误。我得到了结果。但我在MYSQL存储过程中使用它。然后,当我尝试运行存储过程时,它给出了这个错误,说“结果由多行组成”。 这是因为我有一个月份和年份的GROUP BY,它将为产品生成多个记录。但这就是我想要的功能。 处理这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为我采取的方法是完全错误的,因为第二个SQL返回多行,为了做一些结果,我需要把它作为一个光标。所以我按照以下方式重新编写了SP,现在工作正常,

DROP PROCEDURE IF EXISTS DWH.product_stats;
CREATE PROCEDURE DWH.product_stats(OUT int_return INT)
BEGIN
DECLARE vc_sku, 
      vc_prod_id    VARCHAR(100);

DECLARE not_found INT DEFAULT 0;

DECLARE cur_sku CURSOR FOR
  SELECT product_id, sku FROM product LIMIT 0,10;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;

OPEN cur_sku;
REPEAT
  FETCH cur_sku INTO vc_prod_id, vc_sku;
  IF NOT not_found THEN
  SET @vc_prod_id = vc_prod_id;
  -- Number of Views and Favs
  BEGIN
    DECLARE int_views,
            int_fav,
            int_month, 
            int_year INT;

    DECLARE not_found_ev INT DEFAULT 0;

    DECLARE cur_event CURSOR FOR
      SELECT  
        COUNT(CASE WHEN event_type_id = 1 THEN 1 END) AS views,
        COUNT(CASE WHEN event_type_id = 5 THEN 1 END) AS favs,
        MONTH(logged_at) AS log_mon, 
        YEAR(logged_at) AS log_year 
        FROM report_event
        WHERE object_id = @vc_prod_id
        GROUP BY log_mon, log_year
        ORDER BY log_year, log_mon;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found_ev = 1;  

      OPEN cur_event;

      report_event_loop : LOOP 

        FETCH cur_event INTO int_views, int_fav, int_month, int_year; 
        IF not_found_ev THEN
          CLOSE cur_event;
          LEAVE report_event_loop;
        END IF;
        -- DEBUG
        SELECT @vc_prod_id, vc_sku, vc_prod_id, int_views, int_fav, int_month, int_year ;
      END LOOP;
      SET not_found_ev = 0;
  END;
 END IF;
 UNTIL not_found END REPEAT ;
 CLOSE cur_sku;
END;