sqlite.swift如何做子查询

时间:2017-09-04 08:39:40

标签: sqlite sqlite.swift

我正在尝试查询以从消息表中获取特定对话中的最新N条消息。我认为这是正确的sql:

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]!)")
        }
    }

row [index]的类型为Binding,所以我不确定如何在那里检索值。求救!

由于

1 个答案:

答案 0 :(得分:0)

好的,所以看起来子查询可能太复杂而无法在sqllite.swift中表达。我最终使用原始sql查询。您可以通过转换绑定来检索结果:

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