表产品
id name price quantity total
1 food 50 1 50
2 drink 20 2 40
3 dress 100 3 300
如何声明一个列是两列产品的表?
我有这段代码:
CREATE TABLE [dbo].[Orders] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[ProductName] NCHAR (70) NULL,
[Price] INT NULL,
[Quantity] INT NULL,
[Total] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
答案 0 :(得分:2)
听起来像是想要VIEW
。
他们的例子正是你所描述的
mysql> CREATE TABLE t (qty INT, price INT);
mysql> INSERT INTO t VALUES(3, 50);
mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
mysql> SELECT * FROM v;
+------+-------+-------+
| qty | price | value |
+------+-------+-------+
| 3 | 50 | 150 |
+------+-------+-------+
答案 1 :(得分:1)
你可以尝试这个伴侣:
DROP TRIGGER IF EXISTS trg_product_total;
DELIMITER //
CREATE TRIGGER trg_product_total AFTER INSERT ON product
FOR EACH ROW BEGIN
SET @price = NULL, @quantity = NULL;
SELECT price INTO @price FROM product
WHERE id = NEW.id;
SELECT quantity INTO @quantity
WHERE id = NEW.id;
UPDATE product SET total = @price * @quantity
WHERE id = NEW.id;
END;
如果您在将产品插入数据库之前并不真正想要处理product.total,则可以使用这种方法。
每次将新记录添加到表格中时,触发器都会执行,其中总列的预期插入值为“空白”和“空白”。或者' 0' 0取决于您的默认值。
但我认为如果你在插入之前计算它会更好。
流程如下:
Application side
1. get price and quantity for the product
2. calculate for the total
3. insert values into the query
4. execute query