是否可以按主键排序查询?
Posted
技术标签:
【中文标题】是否可以按主键排序查询?【英文标题】:Is it possible to order a query by primary key? 【发布时间】:2014-05-07 19:23:18 【问题描述】:我有一个包含UTCTime
类型字段的实体定义。
Foo
time UTCTime
...
我想选择一系列按时间排序的实体。如果两个实体的时间相等,我不在乎哪个先到,我只希望每次的顺序都相同。实体键是唯一的,似乎按键排序是完美的 选择。
是否可以执行selectList 之类的查询并按主键对匹配的行进行排序? 或者
是否可以在实体中包含主键? 或者,有没有其他方法来确定行的顺序?当然,我总是可以只请求按时间排序,然后自己按键排序返回的列表。但这排除了使用SelectOps OffsetBy
和LimitTo
,因为我无法事先知道会有多少相同时间的实体。
【问题讨论】:
我不确定,但也许Asc
和Desc
SelectOps 可以用于此目的?
@chi 这些仅适用于实体值本身的字段,而不适用于键。
【参考方案1】:
我不确定SelectOpt
s 是否仅适用于实体值,因此我在一小段代码中检查了这一点。假设一个实体如下所示:
EntityA
key Text
time UTCTime
deriving Show
您可以只列出您感兴趣的SelectOpt
s 并获得理想的输出。
示例代码如下所示:
main :: IO ()
main = runSqlite ":memory:" $ do
runMigration migrateAll
currentTime <- liftIO getCurrentTime
-- insert some data
_ <- insert $ EntityA "first" currentTime
_ <- insert $ EntityA "second" currentTime
_ <- insert $ EntityA "third" currentTime
_ <- insert $ EntityA "fourth" currentTime
currentTime <- liftIO getCurrentTime
-- insert more data
_ <- insert $ EntityA "fifth" currentTime
_ <- insert $ EntityA "sixth" currentTime
_ <- insert $ EntityA "seventh" currentTime
_ <- insert $ EntityA "eighth" currentTime
currentTime <- liftIO getCurrentTime
-- insert more data
_ <- insert $ EntityA "this one will be first" currentTime
sorted <- selectList [] [Desc EntityATime, Asc EntityAId]
mapM_ (liftIO . print) sorted
输出是:
Migrating: CREATE TABLE "entity_a"("id" INTEGER PRIMARY KEY,"key" VARCHAR NOT NULL,"time" TIMESTAMP NOT NULL)
Entity entityKey = Key unKey = PersistInt64 9, entityVal = EntityA entityAKey = "this one will be first", entityATime = 2014-05-07 20:15:35.627561 UTC
Entity entityKey = Key unKey = PersistInt64 5, entityVal = EntityA entityAKey = "fifth", entityATime = 2014-05-07 20:15:35.627026 UTC
Entity entityKey = Key unKey = PersistInt64 6, entityVal = EntityA entityAKey = "sixth", entityATime = 2014-05-07 20:15:35.627026 UTC
Entity entityKey = Key unKey = PersistInt64 7, entityVal = EntityA entityAKey = "seventh", entityATime = 2014-05-07 20:15:35.627026 UTC
Entity entityKey = Key unKey = PersistInt64 8, entityVal = EntityA entityAKey = "eighth", entityATime = 2014-05-07 20:15:35.627026 UTC
Entity entityKey = Key unKey = PersistInt64 1, entityVal = EntityA entityAKey = "first", entityATime = 2014-05-07 20:15:35.626622 UTC
Entity entityKey = Key unKey = PersistInt64 2, entityVal = EntityA entityAKey = "second", entityATime = 2014-05-07 20:15:35.626622 UTC
Entity entityKey = Key unKey = PersistInt64 3, entityVal = EntityA entityAKey = "third", entityATime = 2014-05-07 20:15:35.626622 UTC
Entity entityKey = Key unKey = PersistInt64 4, entityVal = EntityA entityAKey = "fourth", entityATime = 2014-05-07 20:15:35.626622 UTC
如果您有兴趣,我可以发布示例项目(位于fpcomplete.com),但我想这很好地说明了这一点。
【讨论】:
老实说,我从来没有想过要这样做。我一直认为 key 和 value 是完全分开的。非常感谢!以上是关于是否可以按主键排序查询?的主要内容,如果未能解决你的问题,请参考以下文章