postgresql - Select limited set of fields from inner query with preserved order -
i've got sql query involves one-to-many relationships order by clause:
select s0_.id, s0_.created_at, s5_.sort_order surveys_submits s0_ inner join surveys_answers s3_ on s0_.id = s3_.submit_id inner join surveys_questions s4_ on s3_.question_id = s4_.id inner join surveys_questions_references s5_ on s4_.id = s5_.question_id order s0_.created_at desc, s5_.sort_order asc this query returns following results:
id | created_at | sort_order ----+---------------------+----------- 218 | 2014-03-18 12:21:09 | 1 218 | 2014-03-18 12:21:09 | 2 218 | 2014-03-18 12:21:09 | 3 218 | 2014-03-18 12:21:09 | 4 218 | 2014-03-18 12:21:09 | 5 217 | 2014-03-18 12:20:57 | 1 217 | 2014-03-18 12:20:57 | 2 217 | 2014-03-18 12:20:57 | 3 ... 214 | 2014-03-18 12:18:01 | 4 214 | 2014-03-18 12:18:01 | 5 213 | 2014-03-18 12:17:48 | 1 213 | 2014-03-18 12:17:48 | 2 213 | 2014-03-18 12:17:48 | 3 213 | 2014-03-18 12:17:48 | 4 213 | 2014-03-18 12:17:48 | 5 now, need modify query in way return first 25 distinct ids begining preserved order.
i've tried this:
select distinct id ( select ... order ... ) inner_query order created_at desc, sort_order asc limit 25 offset 0; but doesn't work:
error: select distinct, order expressions must appear in select list line 16: created_at desc, ^ ********** error ********** ...and can't add created_at , sort_order columns select clause cause result in duplicated ids, first query.
select * ( select distinct on (s0_.id) s0_.id, s0_.created_at, s5_.sort_order surveys_submits s0_ inner join surveys_answers s3_ on s0_.id = s3_.submit_id inner join surveys_questions s4_ on s3_.question_id = s4_.id inner join surveys_questions_references s5_ on s4_.id = s5_.question_id order s0_.id, s0_.created_at desc, s5_.sort_order asc ) s order created_at desc, sort_order asc limit 25 select distinct on ( expression [, ...] ) keeps first row of each set of rows given expressions evaluate equal. distinct on expressions interpreted using same rules order (see above). note "first row" of each set unpredictable unless order used ensure desired row appears first.
Comments
Post a Comment