gpt4 book ai didi

haskell - 是否可以按主键对查询进行排序?

转载 作者:行者123 更新时间:2023-12-03 21:47:23 25 4
gpt4 key购买 nike

我有一个实体定义,其中包含 UTCTime 类型的字段。

Foo
time UTCTime
...

我想选择一系列按时间排序的实体。如果两个实体有相同的时间,我不关心哪个先到,我只希望每次的顺序都相同。实体键是唯一的,似乎按键排序是完美的选择。

是否可以执行类似 selectList 的查询并按主键对匹配的行进行排序?或者

  • 是否可以在实体中包含主键?
  • 或者,是否有任何其他方法可以确定行的顺序?

当然,我总是可以只请求按时间排序,然后自己按键排序返回的列表。但这排除了使用 SelectOp s OffsetByLimitTo,因为我无法事先知道会有多少个具有相同时间的实体。

最佳答案

我不确定 SelectOpt 是否仅适用于实体值,因此我在一小段代码中进行了检查。假设一个实体看起来像这样:

EntityA
key Text
time UTCTime
deriving Show

您可以只列出您感兴趣的 SelectOpt 并获得所需的输出。

示例代码如下所示:

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 上),但我想这很好地说明了这一点。

关于haskell - 是否可以按主键对查询进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23526524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com