2017-09-04 56 views
0

我正在嘗試查詢以從消息表中獲取特定對話中的最新N個消息。我認爲這是正確的SQL:sqlite.swift如何執行子查詢

select * from 
(select * from messages where convoId = to order by timestamp DESC limit 10) 
order by timestamp ASC; 

我在sqlite.swift嘗試這樣的:

static let table = Table("messages") 
let query = (table.filter(convoId == to).order(timestamp.desc).limit(10)).select(table[*]).order(timestamp.asc) 

這是行不通的,一旦消息的金額將過去的極限。有什麼方法可以查看sqlite.swift查詢生成的sql數據嗎?有什麼建議麼?

編輯:我也嘗試了原始SQL查詢,但現在我不知道如何提取結果。我覺得這應該是最後一招:

let toQuoted = "'" + to + "'" 
    let subQueryStr: String = [ 
     "(SELECT * FROM", 
     MessageDataHelper.TABLE_NAME, 
     "WHERE", 
     MessageDataHelper.CONVO_ID, "=", toQuoted, "ORDER BY", MessageDataHelper.TIMESTAMP, "DESC LIMIT", String(5), ")" 
    ].joined(separator: " ") 

    let queryStr: String = [ 
     "SELECT * FROM", 
     subQueryStr, 
     ["ORDER BY", MessageDataHelper.TIMESTAMP, "ASC;"].joined(separator: " ") 
    ].joined(separator: "\n") 

    let stmt = try db.prepare(queryStr) 
    for row in stmt { 
     // ? how can this be used to create model structure 
     for (index, name) in stmt.columnNames.enumerate() { 
      print ("\(name)=\(row[index]!)") 
     } 
    } 

行[指數]是一種類型的結合,所以我不能確定如何檢索值出現。請幫助!

感謝

回答

0

好了,所以看起來像子查詢可能會非常複雜,sqllite.swift來表達。我結束了與原始的SQL查詢。這裏提到您可以通過鑄造結合檢索結果:

Getting results from arbitrary SQL statements with correct binding in SQLite.swift

+0

如果你曾經夢想斯威夫特的SQLite庫,它提供了相同的行消費,只要您使用SQL Builder或原始的SQL查詢,檢查出[中GRDB](http://github.com/groue/GRDB.swift)。 –