UNION with ORDER BY RAND() works only with LIMIT on MySQL -


i put on sqlfiddle , works intended, on university mysql engine, works differently: http://sqlfiddle.com/#!9/9d975f/3

i have list contains words , categories:

id, word, category 1, red, color 2, blue, color 3, brick, item 4, rock, item 5, hat, item 6, glove, item 7, cape, item 8, cup, item 9, love, feeling ... etc 

i need 8 words, first 4 mix of colors , items, last 4 items, , words must randomly selected , unique.

for example: blue, hat, rock, red, brick, glove, cup, cape (color, item, item, color, item, item, item, item)

i not in single query, first ran query list of ids first half, example, 1, 2, 4, 5 (red, blue, rock, hat)

this works:

select * word id in (1, 2, 4, 5) order rand()  

always giving me words 1, 2, 4 , 5 in random order. when used in union subquery:

select * (select * word id in (1, 2, 4, 5) order rand() )  union  select * (select * word id not in (1, 2, 4, 5) , category='item' order rand() limit 4) b 

the first 4 words in order, giving me, example: 1, 2, 4, 5, 8, 3, 7, 6. however, if specify limit:

select * (select * word id in (1, 2, 4, 5) order rand() limit 4)  union  select * (select * word id not in (1, 2, 4, 5) , category='item' order rand() limit 4) b 

it works intended. red, blue, rock, , hat in random order, followed 4 more items in random order, not including rock , hat.

i understand union has list of rules remove duplicates, i'm confused why including limit change behavior.

ideally, done in single query, couldn't figure out how not in on 2nd half of union refers words selected in 1st half of union.

as noticed, union has deduplicating function. function works hash merge. nullifies effect of order by clauses in subqueries contributing merge. (some dbmss "you can't use order by in subquery bound union", mysql lets it.)

you try work around problem.

select word    (        select word, rand() random word  id in (1, 2, 4, 5)         union        select word, 1.0+rand() random word id not  (1, 2, 4, 5)     ) w   order random 

this ordering in outer query, not subquery, , achieve kind of ordering want.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -