问题
I'm trying to make simple pagination using Slick with Postgres, but it does not work as expected.
// Table
// "users_pkey" PRIMARY KEY, btree (id)
// "users_id_idx" btree (id)
val id: Column[Option[Long]] = column("id", O.PrimaryKey, O.AutoInc, O.DBType(BigSerial))
// Pagination queries
users.drop(0).take(20).sortBy(_.id.desc).list
users.drop(20).take(20).sortBy(_.id.desc).list
But results are not ordered as expected. Users ordered by id
on inside page, e.g. first page will be like 40, 35, 34 ... 4, 2
and second 39, 38, 36, ... 3, 1
.
回答1:
The issue is that you are sorting after taking your values. If, in the initial order, 39
is in the 21st position and you take and sort the first 20 values, it cannot be sorted into the correct place, as you sort without it there.
If you want correct ordering, you should sort your users before taking the chunks, e.g:
val sortedUsers = users.sortBy(_.id.desc)
sortedUsers.drop(0).take(20).list
sortedUsers.drop(20).take(20).list
来源:https://stackoverflow.com/questions/28836336/scala-slick-wrong-pagination-w-postgres