masize
masize

Reputation: 109

Mysql Cursor not sorting result in correct order

This is an abstraction of my original code as it´ll be easier to read for you guys.

I´m new to Mysql Storage procedures and from Cursors.

Whats happening is that Cursor is not bringing the results properly sorted as I set the ORDER BY instruction on the query.

Here´s all the structure and data for the tables to reproduce the issue.

Log Table :

    DROP TABLE IF EXISTS `log`;
    CREATE TABLE `log` (
      `key` text NOT NULL,
      `value` text NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Test Table :

    DROP TABLE IF EXISTS `test1`;
    CREATE TABLE `test1` (
      `ID` bigint(8) unsigned NOT NULL AUTO_INCREMENT,
      `price` float(16,8) NOT NULL,
      PRIMARY KEY (`ID`),
      KEY `price` (`price`)
    ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

Test table data :

    INSERT INTO `test1` (`price`)
    VALUES (100),(200),(300),(400),(300),(200),(100);

Query:

    SELECT *
    FROM `test1`
    ORDER BY price DESC;

Expected results works fine with query directly:

Stored Procedure

    DROP PROCEDURE IF EXISTS `test_proc1`;
    DELIMITER ;;

    CREATE DEFINER=`root`@`localhost` PROCEDURE `test_proc1`()
    BEGIN

      DECLARE done INT DEFAULT 0;
      DECLARE ID BIGINT(8);
      DECLARE price FLOAT(16,8);

      DECLARE cur1 CURSOR FOR
      SELECT * FROM `test1` ORDER BY price DESC; #Exact Query

      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

      START TRANSACTION;
        OPEN cur1;
        #Cleaning log
        TRUNCATE `log`;
        read_loop:
        LOOP
          FETCH cur1 INTO ID,price;
          IF done = 1 THEN
            LEAVE read_loop;
          END IF;
          #Inserting data to log
          INSERT INTO `log`
          VALUES (ID,price);
        END LOOP read_loop;

        CLOSE cur1;
      COMMIT;

    #Bring log for result
    SELECT * FROM log;

    END;;
    DELIMITER ;

Call procedure

    CALL test_proc1();

The CURSOR has exactly the same query as I posted at the top, you can check that on the Stored Procedure. But when I loop through it, I get another order.

Whats going on? Can somebody help me on this? I also tried nesting the query like this with no fix at all.

SELECT * FROM(
SELECT *
FROM `test1`
ORDER BY price DESC) AS tmp_tbl

Upvotes: 5

Views: 2792

Answers (1)

BlitZ
BlitZ

Reputation: 12168

Looks like you have a "variable collision". Variable price is used instead of table column with that exact name. Change variable name, or use table alias like this:

SELECT * FROM `test1` as `t` ORDER BY `t`.`price` DESC;

Upvotes: 5

Related Questions