Sorted inside Union

    A feature of sorting inside union.
    Thank you funca I ’ll leave a post - maybe someone will find the main meaning useful - " You need to sort the result, not the intermediate data ."
    1. CREATE TABLE `t1` (
    2. `id1` int( 10 ) unsigned NOT NULL default '0',
    3. `id2` int( 10 ) unsigned NOT NULL ,
    4. `k1` decimal( 6, 5 ) unsigned NOT NULL default '0.00000',
    5. `k2` int( 10 ) unsigned NOT NULL default '0',
    6. PRIMARY KEY ( `id1` , `id2` ) ,
    7. KEY `k2` ( `id1` , `k2` )
    8. ) ENGINE = MEMORY;
    .


    engine memory is not a key point - I checked the same thing on MyISAM

    and fill it with data similar to the one below.
    1. for($i=0;$i<100;$i++){
    2.   $i->query('REPLACE INTO `t1` (`id1`, `id2`, `k1`, `k2`)VALUES (?d, ?d, ?f, ?d)',
    3.     rand(0,99999), rand(0,5), rand(2,99999)/50000, rand(0,20)
    4.   );
    5. }
    * This source code was highlighted with Source Code Highlighter.


    and look at the result of such a query:

    1. (
    2.   SELECT `id1`, `k1`, `k2`
    3.   FROM `t1`
    4.   WHERE `id2`=3 AND `k2`=13
    5.   ORDER BY `k1` DESC
    6. )
    7. UNION (
    8.   SELECT `id1`, `k1`, `k2`
    9.   FROM `k1`
    10.   WHERE `id2`=3 AND `k2`!=13
    11.   ORDER BY `k1` DESC
    12. )


    here it is, for the above example:
    id1 k1 k2
    2726 1.50194 13
    88207 0.25084 13
    37274 0.96550 11
    11059 0.42600 6
    11139 1.90196 4
    63593 1.42970 5
    65273 1.44950 18
    28721 0.79328 15
    70946 0.87576 4
    96673 1.71290 14
    49207 1.92928 17
    40697 1.82320 18
    


    The bug in our opinion is that in the sample generated by the second query of the union there is no sorting by the middle column.
    Can any of the habrasociety shed light on such behavior?

    By the way, of course, we also want to share a solution to this problem:
    1. SELECT `id1` , `k1` , `k2`
    2. FROM `t1`
    3. WHERE `id2` =3
    4. ORDER BY if( `k2` =13, 0, 1 ) , `k1` DESC


    2726 1.50194 13
    88207 0.25084 13
    49207 1.92928 17
    11139 1.90196 4
    40697 1.82320 18
    96673 1.71290 14
    65273 1.44950 18
    63593 1.42970 5
    37274 0.96550 11
    70946 0.87576 4
    28721 0.79328 15
    11059 0.42600 6
    

    Also popular now: