考虑下表:
ID : int
Quantity : smallint
Price : float(5,2)
我尝试运行以下查询:
SELECT ID, SUM(Quantity * Price) FROM test GROUP BY ID;
正如预期的那样,这在 MySQL Workbench 中正确执行,但是在 Qt 中却没有发生同样的情况。
让表格填充以下内容:
| ID | Quantity | Price |
| 1 | 3 | 1.00 |
| 1 | 3 | 2.00 |
| 2 | 3 | 3.00 |
并在 Qt 中进行以下实现:
qDebug() << "Running...";
QSqlQuery query(myDB);
query.prepare(" SELECT ID, SUM(Quantity * Price) FROM test GROUP BY ID;");
if(!query.exec())
throw "Error";
else{
qDebug() << "Size: " << query.size();
while(query.next()){
qDebug() << query.value(0).toInt();
qDebug() << query.value(1).toFloat();
}
}
qDebug() << "End!";
结果是:
Running...
Size: 2
End!
因此,即使返回的大小是 2,循环也永远不会运行。
奇怪的是,当我将 Price 变量更改为 int 时,问题就消失了。
最佳答案
query.prepare(" SELECT ID, SUM(Quantity * Price) FROM teste GROUP BY ID;");
看起来您输错了表名“teste”
关于c++ - 使用 QT 从 MySQL 返回 SUM 值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654548/