
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 ."
engine memory is not a key point - I checked the same thing on MyISAM
and fill it with data similar to the one below.
and look at the result of such a query:
here it is, for the above example:
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:
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 ."
- CREATE TABLE `t1` (
- `id1` int( 10 ) unsigned NOT NULL default '0',
- `id2` int( 10 ) unsigned NOT NULL ,
- `k1` decimal( 6, 5 ) unsigned NOT NULL default '0.00000',
- `k2` int( 10 ) unsigned NOT NULL default '0',
- PRIMARY KEY ( `id1` , `id2` ) ,
- KEY `k2` ( `id1` , `k2` )
- ) 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.
- for($i=0;$i<100;$i++){
- $i->query('REPLACE INTO `t1` (`id1`, `id2`, `k1`, `k2`)VALUES (?d, ?d, ?f, ?d)',
- rand(0,99999), rand(0,5), rand(2,99999)/50000, rand(0,20)
- );
- }
* This source code was highlighted with Source Code Highlighter.
and look at the result of such a query:
- (
- SELECT `id1`, `k1`, `k2`
- FROM `t1`
- WHERE `id2`=3 AND `k2`=13
- ORDER BY `k1` DESC
- )
- UNION (
- SELECT `id1`, `k1`, `k2`
- FROM `k1`
- WHERE `id2`=3 AND `k2`!=13
- ORDER BY `k1` DESC
- )
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:
- SELECT `id1` , `k1` , `k2`
- FROM `t1`
- WHERE `id2` =3
- 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