查找今天(Postgres, c++, QT)的最高列值



编辑:下面的查询不起作用,但答案中给出的概念仍然适用。查看此处如何修复postgres

中的查询sqlite IFNULL()我在Postgresql中有一个名为"transaction"的表。该表的主键是与(id, date)的复合键,其中id是一个int, date是一个时间戳。每天,第一份订单都是从一号订单开始的。当天的下一个订单将是#2,然后是#3,以此类推,直到第二天再次出现#1。

我不确定我将如何改变这个SQL查询找到最大的事务ID,特别是从今天然后增量1到它。或者从1开始,如果今天没有交易。到目前为止,我唯一能做的就是,如果根本没有交易,就从1开始,或者根据所有日期中最高的ID增加。

/* Insert Transaction */
bool dbmanager::addTransaction(const int& custPhone=0, const int& totalCents=0, const qstr& items="",
const qstr& paymentType="", const int& tender=0, const int& change=0,
const int& cardNum=0, const int& cardExp=0, const int& cardCVV=0, QWidget* from=nullptr)
{
QSqlQuery q;
// TODO: This query increments the largest order number that exists across all dates. Make it so the order number is 1+ the max order number from today
q.prepare("insert into pos_schema.transaction values( (select ifnull(max(id), 0) + 1 from pos_schema.transaction), NOW(), "
":phone, :total_cents, :items, :payment_type, :tender, :change, :card_number, :card_exp, :card_cvv);");
q.bindValue(":phone",custPhone);
q.bindValue(":total_cents", totalCents);
q.bindValue(":items", items);
q.bindValue(":payment_type", paymentType);
q.bindValue(":tender", tender);
q.bindValue(":change", change);

QString cryptCardNum = crypt.encryptToString(qstr::number(cardNum));
QString cryptCardExp = crypt.encryptToString(qstr::number(cardExp));
QString cryptCardCVV = crypt.encryptToString(qstr::number(cardCVV));
q.bindValue(":card_number", cryptCardNum);
q.bindValue(":card_exp", cryptCardExp);
q.bindValue(":card_cvv", cryptCardCVV);
if (q.exec())
return true;
qDebug() << "Transaction Insertion Error:" << q.lastError().text();
displayError("Insertion", from, q);
return false;
}

您需要更新子选择

select ifnull(max(id), 0) + 1 from pos_schema.transaction

变成

SELECT
ifnull(max(id), 0) + 1
FROM pos_schema.transaction
WHERE
pos_schema.transactiondate.date::date = CURRENT_DATE

请注意,您的字段date应该是真正的date类型,而不是timestamp。否则,如果您的主键具有不同的时间戳,则无法防止为同一日期插入两个重复的id。

最新更新