QSqlQuery忽略SQLite DB的排序顺序

时间:2014-11-16 23:04:14

标签: c++ qt sqlite

我的QSqlQuery返回的结果始终采用相同的顺序,无论ORDER BY状态如何:

void Sy_loggingModel::reload()
{
    auto query = d_->buildQuery();
    query.setForwardOnly( true );
    if ( !query.exec() ) {
        throw Sy_exception( QObject::tr( "Failed to query logging data: " ) +
                            query.lastError().text() );
    }

    beginResetModel();

    qDebug() << query.lastQuery()
             << d_->filter_        // First ? param
             << d_->sortedColumn_; // Second ? param

    d_->entries_.clear();
    while ( query.next() ) {
        auto timestamp = query.value( 1 ).toLongLong();
        auto level = query.value( 2 ).toInt();

        d_->entries_ << Sy_loggingModel_d::Entry{
                            query.value( 0 ).toLongLong(),
                            QDateTime::fromMSecsSinceEpoch( timestamp ).toString(),
                            static_cast< Sy_loggerInterface::DebugLevel >( level ),
                            query.value( 3 ).toString() };

        qDebug() << "\t" << query.value( 0 ).toLongLong()
                         << timestamp
                         << level
                         << query.value( 3 ).toString();
    }

    endResetModel();
}

在排序顺序之间交替生成此输出:

"SELECT rowid, timestamp, debugLevel, message FROM Sy_logger WHERE rowid >= ? AND debugLevel IN ( 0, 1, 2 ) ORDER BY ? DESC;" 0 1
     1 1415399097350 0 "Opened database ./logs/Syren2.log"
     2 1415399097382 1 "Listening on port 23000"
     3 1415399418377 2 "New log rotation settings received, Metric: 0, Interval: 720"
     4 1416178611851 2 "Opened database ./logs/Syren2.log"
     5 1416178611852 2 "Listening on port 23000"
     6 1416178612776 2 "New log rotation settings received, Metric: 0, Interval: 720"


"SELECT rowid, timestamp, debugLevel, message FROM Sy_logger WHERE rowid >= ? AND debugLevel IN ( 0, 1, 2 ) ORDER BY ? ASC;" 0 1
     1 1415399097350 0 "Opened database ./logs/Syren2.log"
     2 1415399097382 1 "Listening on port 23000"
     3 1415399418377 2 "New log rotation settings received, Metric: 0, Interval: 720"
     4 1416178611851 2 "Opened database ./logs/Syren2.log"
     5 1416178611852 2 "Listening on port 23000"
     6 1416178612776 2 "New log rotation settings received, Metric: 0, Interval: 720"

从命令行使用时,SQL语句返回预期的结果集。有什么建议?我正在使用Qt v5.3.2。

1 个答案:

答案 0 :(得分:2)

documentation说:

  

如果ORDER BY表达式是一个常数整数K,则该表达式被视为结果集的第K列的别名。

但是,参数不被视为常量,因此用于此参数的值将用作恰好对所有行都相同的表达式。

如果要按不同的列排序,则必须动态构造SQL语句。