我使用下面的mysql查询在用户向他的帐户广告资金后将数据从oldtable插入到newtable。如果用户将一些钱存入他的账户,我想输入accbal列的值为信用列值和accbal(用户旧账户余额)的总和。即我想在调整借方贷方金额后添加具有用户账户结果余额的mysql行。请告诉我如何使用mysql和php。
$sql2="INSERT INTO newtable (emailadd, credit, debit, accbal, txtime, txnid) SELECT buyeremailaddr, 'balcredit', '0', QUESTION, pptxtime, pptxid FROM oldtable WHERE paymenthash='$item_no' AND paid='1'";
$result2=mysql_query($sql2);
答案 0 :(得分:0)
这可能比您需要的更复杂,但是当您尝试将相关记录的值与最近日期相关联时,它会变得棘手:
INSERT INTO newtable (
emailadd
, credit
, debit
, accbal
, txtime
, txnid
) SELECT buyeremailaddr
, 'balcredit'
, '0'
, credit + accbal
, pptxtime
, pptxid
FROM oldtable
LEFT JOIN (
SELECT emailadd,accbal FROM newtable JOIN (
SELECT emailadd
,MAX(txtime) AS maxdate
FROM newtable GROUP BY emailadd
) AS mt ON mt.maxdate = newtable.txtime
AND mt.emailadd = newtable.emailadd GROUP BY emailadd
) AS nt ON oldtable.buyeremailaddr = nt.emailadd
WHERE paymenthash='$item_no'
AND paid='1'
基本上你加入到按电子邮件分组的新表格,然后又通过电子邮件再次加入自身,以便比较txtime和max txtime以获得最新的accbal值。警告:对于非常大的表,这不能很好地扩展。更好地创建视图,甚至更好地重新评估现有的数据结构