title: MySQL 5.7 wrong results on sort / subquery
body: <p>Very strange results in MySQL 5.7 (specifically 5.7.13-0ubuntu0.16.04.2 ).</p>
  
  <p>I suspect this could be a bug in MySQL. </p>
  
  <pre><code>DROP TABLE IF EXISTS `test_grids_1`;
  CREATE TABLE `test_grids_1` (
    `unq_id` int(11) NOT NULL DEFAULT '0',
    `var_fld` int(11) DEFAULT '0'
  ) ENGINE=InnoDB;
  INSERT INTO `test_grids_1` VALUES
    (1,4500),
    (2,6000);
  
  DROP TABLE IF EXISTS `test_grid_dtl_1`;
  CREATE TABLE `test_grid_dtl_1` (
    `dtl_id` int(11) NOT NULL DEFAULT '0',
    `unq_id` int(11) DEFAULT '0',
    `dtl_var` decimal(14,2) DEFAULT '0.00'
  ) ENGINE=InnoDB;
  INSERT INTO `test_grid_dtl_1` VALUES
    (1,1,2.00),
    (2,1,2.40),
    (3,2,2.30);
  
  
  SELECT
    ( g.calc_var * d.dtl_var ) new_var,
    g.calc_var
  FROM
    (
    SELECT
      unq_id,
      IF ( var_fld  &gt; 5000, ( 1 / var_fld ) , 5000 ) calc_var
    FROM
      test_grids_1
    ) g
  INNER JOIN
    test_grid_dtl_1 d
      ON d.unq_id = g.unq_id;
  
  +--------------+----------+
  | new_var      | calc_var |
  +--------------+----------+
  | 10000.000000 |     5000 |
  | 12000.000000 |     5000 |
  |     0.000383 |   0.0002 |
  +--------------+----------+
  
  SELECT
    ( g.calc_var * d.dtl_var ) new_var,
    g.calc_var
  FROM
    (
    SELECT
      unq_id,
      IF ( var_fld  &gt; 5000, ( 1 / var_fld ) , 5000 ) calc_var
    FROM
      test_grids_1
    ) g
  INNER JOIN
    test_grid_dtl_1 d
      ON d.unq_id = g.unq_id
  ORDER BY
    1;
  
  +--------------+----------+
  | new_var      | calc_var |
  +--------------+----------+
  |     0.000383 |   0.0002 |
  | 10000.000000 |  99.9999 |
  | 12000.000000 |  99.9999 |
  +--------------+----------+
  3 rows in set (0.00 sec)
  </code></pre>
  
  <p>When the sort is included it causes the returned values for certain criteria to be completely incorrect. </p>
  
  <p>Values that are expected to be 5000 are suddenly 99.9999.</p>
  
  <p>If anyone could please check and confirm similar behaviour on other 5.7 installations, it would be great. </p>
  
  <p>Thanks </p>