mysql - Select items from distinct categories, including articles with no category -


this seems pretty simple do. have table of articles has following fields relevant question:

id - integer(11) auto_increment category_id - integer(11) default(-1) 

when article has category, id goes in category_id field. when has no category, column's value -1.

what want select 3 random articles of distinct categories articles table. alone pretty simple do:

select id articles group category_id order rand() limit 3;  

however, don't want group articles no category 1 single category, previous query do. is, want treat each article category_id of -1 being in separate category. how can this?

you can use union create derived table contains

  1. 1 article id per non -1 category
  2. all article ids -1 category

and select 3 random ids table

select id (     select id articles     category_id <> -1     group category_id     union     select id articles     category_id = -1 ) t order rand() limit 3; 

as pointed out in comments, query above return same article id per category id. if that's issue can try query below might run since it's ordering tables rand() twice.

select id (     select id (         select id articles         category_id <> -1         order rand()     ) t      group category_id     union     select id articles     category_id = -1 ) t order rand() limit 3; 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -