Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a table has a column that is the product of two columns

Tags:

sql

tsql

mysql

Table Product

id  name   price   quantity   total

1     food    50      1         50
2     drink   20      2         40
3     dress   100     3         300

How do I declare a table that has a column that is the product of two columns?

I have this code:

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)
);
like image 805
nAPL Avatar asked Oct 19 '22 16:10

nAPL


1 Answers

Sounds like you want a VIEW.

Their example is exactly what you're describing

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 |
+------+-------+-------+
like image 154
Steve Robbins Avatar answered Oct 22 '22 23:10

Steve Robbins