简体   繁体   English

插入表字段后更改其值

[英]Changing the value of a table field after it has already been inserted

I am working with a CMS system, and using a kind of smartform am inserting fields into a table. 我正在使用CMS系统,并使用一种smartform将字段插入表中。

In these fields are the name of a product, quantity and cost. 在这些字段中,是产品名称,数量和成本。

cost and product name are taken from a products table, while quantity is input manually. 成本和产品名称从产品表中获取,而数量则手动输入。

I understand this is not the best architecture, but I am limited with the system I am working with. 我知道这不是最好的体系结构,但是我所使用的系统受到限制。

What I want to do, is change the value of cost after it is inserted, to quantity * cost. 我要做的是将插入后的成本值更改为数量*成本。

What is the easiest way to do this? 最简单的方法是什么?

To change one row: 更改一行:

update  TheTable
set     cost = quantity * cost
where   pk = 123

If you run this multiple times, costs will explode ;-) 如果您多次运行,成本将激增;-)

You can run an UPDATE after the insert, using the identity field of the new product: 您可以在插入后使用新产品的标识字段运行UPDATE

UPDATE products
SET cost = cost * quantity
WHERE product_id = @productId

If you have your hands tied so tightly that you are unable to change the table structure, then you probably won't be able to use a trigger, but here goes anyway. 如果您的双手绑得太紧,以至于无法更改表的结构,那么您可能将无法使用触发器,但是无论如何都可以使用触发器。

This is a sample table structure: 这是一个示例表结构:

DROP TABLE IF EXISTS `products`;

CREATE TABLE `products` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `product` VARCHAR(255),
    `quantity` INT(11) NOT NULL,
    `cost` DECIMAL(6,2) NOT NULL,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Create a trigger which updates the cost prior to it being inserted into the products table: 创建一个触发器,该触发器在将成本插入products表之前对其进行更新:

DELIMITER //
DROP TRIGGER IF EXISTS update_cost//
CREATE TRIGGER update_cost BEFORE INSERT ON products
FOR EACH ROW BEGIN
    SET NEW.cost = NEW.cost * NEW.quantity;
END;
//
DELIMITER ;

Insert a couple of products into the table: 将几个产品插入表中:

INSERT INTO `products` (`product`, `quantity`, `cost`) VALUES
('Acme portable hole', 10, 20),
('Acme jet pack', 1000, 2);

The cost is updated automatically: 费用会自动更新:

SELECT * FROM prodcuts;

+----+--------------------+----------+---------+
| id | product            | quantity | cost    |
+----+--------------------+----------+---------+
|  1 | Acme portable hole |       10 |  200.00 |
|  2 | Acme jet pack      |     1000 | 2000.00 |
+----+--------------------+----------+---------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM