使用一个结果集创建不同的结果集

时间:2015-06-15 09:05:56

标签: mysql sql

通过使用mysql,我得到了像

这样的结果
    count   date        content
    19      2015-01-02  test1
    6       2015-01-02  test2
    3       2015-01-03  test3
    12      2015-01-04  test4
    48      2015-01-04  test5
    10      2015-01-05  test6

我想使用日期值将结果除以不同的结果集。我想要结果集,

    count   date        content
    19      2015-01-02  test1
    6       2015-01-02  test2

    count   date        content
    3       2015-01-03  test3
    12      2015-01-03  test4

    count   date        content
    48      2015-01-04  test5
    10      2015-01-04  test6

是否可以使用一个结果集创建不同的结果集。

1 个答案:

答案 0 :(得分:1)

要在查询条件中对一组查询使用结果集,您需要一个游标。

请查看光标使用情况的基本知识here以及docs

DELIMITER $$

CREATE PROCEDURE group_results_by_date 
BEGIN

 DECLARE v_finished INTEGER DEFAULT 0;
 DECLARE cdate DATE DEFAULT "2015-01-01";

 -- declare cursor for getting list of dates
 DEClARE date_cursor CURSOR FOR 
    SELECT DISTINCT (date) FROM yourtable;

 -- declare NOT FOUND handler
 DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET v_finished = 1;

 OPEN date_cursor;

 get_content: LOOP

 FETCH date_cursor INTO cdate;

 IF v_finished = 1 THEN 
 LEAVE get_content;
 END IF;

 -- Select query for different dates
 Select count, date, content from yourtable where date = cdate;

 END LOOP get_content;

 CLOSE date_cursor;

END$$

DELIMITER ;

您可以通过

调用此过程
CALL group_results_by_date();
相关问题