sqlite3 - select statement order by top 3 from one column and the rest by another column -


i need use 2 different sortorders. want select top 3 based on column popularitysortorder asc , rest sortorder asc.

table

--------------------------------------------------------------------------------------- |   id   |      product         |   price   |   sortorder   |   popularitysortorder   | ---------------------------------------------------------------------------------------     1     samsung galaxy s6 edge     100            1                   2      2          iphone 6              100            2                   1      3          iphone 5s             100            4                   4      4       samsung galaxy s6        100            6                   3      5       google nexus 6           100            3                   5      6       google nexus 5           100            5                   7  

i've tried following select, unfourtanly unsuccessful:

select * (    select * temp1 t1 order popularitysortorder limit 3    union    select * temp1 t2 t2.id <> t1.id order sortorder )  order popularitysortorder, sortorder asc 

expected result:

--------------------------------------------------------------------------------------- |   id   |      product         |   price   |   sortorder   |   popularitysortorder   | ---------------------------------------------------------------------------------------     2          iphone 6              100            2                   1 *     1     samsung galaxy s6 edge     100            1                   2 *     4       samsung galaxy s6        100            6                   3 *     5       google nexus 6           100            3 *                 5      3          iphone 5s             100            4 *                 4      6       google nexus 5           100            5 *                 7  

edit: using sqlite version 3.7

fiddle

t1 not visible in other part of union query.

you can duplicate popularity query, or use temporary view, or (in sqlite 3.8.3 or later) common table expression:

with mostpopular3 (   select * temp   order popularitysortorder   limit 3 ) select * mostpopular3 union select * (   select * temp   id not in (select id mostpopular3)   order sortorder ) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

php - Find a regex to take part of Email -

javascript - Function overwritting -