我进行了ajax活动表编辑,以更改当前产品的价格。我想要做的是在更改价格之前先插入价格,然后插入更新的价格。原因是因为我想显示更新价格的变化。示例:当前价格为$ 54.00,我将其更改为$ 57.00。我需要全天记录价格变化日志,并显示$ 3.00的价格变化。我如何插入旧价格,同时也插入更新的价格。谢谢。
最佳答案
我建议您像这样制作价格表
table price
-----------
id unsigned integer autoincrement primary key
article_id integer /*link to articletable*/
valid_from date
valid_until date
amount decimal(10,2) /*always use decimal for money*/
然后,您可以使用以下4个查询插入新价格。
/*hide changes from the rest of the world until we are done*/
START TRANSACTION
/*invalidate the latest existing price in the price table*/
UPDATE price
SET valid_until = DATESUB(CURDATE(),INTERVAL 1 DAY)
WHERE article_id = '100' ORDER BY valid_until DESC LIMIT 1
/*the order by selects the latest item, the limit does only 1 update*/
/*insert the new price*/
INSERT INTO PRICE (article_id, valid_from, valid_until, amount)
VALUES ('100', CURDATE(), DATEADD(CURDATE(),INTERVAL 100 YEAR), '99.95')
/*show changes to the rest of the world*/
COMMIT
您需要交易,否则就有价格表不同步的风险。在价格表上将表类型设置为
InnoDB
。您的其他表可以是
MyISAM
,只需确保price
表是InnoDB
。您现在可以使用以下方法选择价格:
SELECT article.name
,price.amount as price_per_item
,purchase.qty as number_of_items
,price.amount * purchase.qty as amount
FROM purchase
INNER JOIN article ON (article.id = purchase.article_id)
INNER JOIN price ON (price.article_id = purchase.article_id)
AND (purchase.transactiondate BETWEEN price.valid_from and price.valid_until)
WHERE purchase.id = '458'
关于php - MySQL插入当前结果,然后插入新结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6141335/