mysql user variable assignement with count(*)

后端 未结 1 1456
后悔当初
后悔当初 2021-01-27 15:36

I try to do query with a user variable, but I don\'t understand why, i can\'t update the variable in the query. I want to sum the grouped result for each day to do a chart. That

相关标签:
1条回答
  • 2021-01-27 16:41

    As @JagaSrik said, there is a need to more information about your data and tables to give right answer. However, if you need to change a table like this:

    name                |     date      |  id
    -----------------------------------------
    total Inscription   |   2017-07-10  |   2
    total Inscription   |   2020-04-20  |   2
    total Inscription   |   2020-04-21  |   3
    total Inscription   |   2020-06-17  |   4
    total Inscription   |   2020-06-18  |   2
    

    to something like this:

         date      |  total
    -----------------------------------------
       2017-07-10  |   2
       2020-04-20  |   4
       2020-04-21  |   7
       2020-06-17  |   11
       2020-06-18  |   13
    

    you can use CURSOR.

    For this example:

    DELIMITER $$
    CREATE PROCEDURE `countIds`()
    BEGIN
        DECLARE finished INTEGER DEFAULT 0;
        DECLARE total INTEGER DEFAULT 0;
        DECLARE theCount INTEGER DEFAULT 0;
        DECLARE theDate varchar(100) DEFAULT "";    
    
            DEClARE curCount 
            CURSOR FOR 
                SELECT `id`,`date` FROM table1;
    
            DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET finished = 1;
            
        OPEN curCount;
    
        getCount: LOOP
            FETCH curCount INTO theCcount,theDate;
            IF finished = 1 THEN 
                LEAVE getCount;
            END IF;
            SET total = total + theCount;
            select theDate, total;
        END LOOP getCount;
        CLOSE curCount;       
    
    END$$
    DELIMITER ;
    

    Nevertheless CURSOR is a way to do your work and there may be more effective methods.

    0 讨论(0)
提交回复
热议问题