Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table in mysql with one column containing sum of another two columns value

Is it possible in mysql to create a table with a column that combines two column values? something like this:

create table test1 (
    number1 int,
    number2 int,
    total int DEFAULT (number1+number2)
);

or like this :

CREATE TABLE `Result` (
    `aCount` INT DEFAULT 0,
    `bCount` INT DEFAULT 0,
    `cCount` =  `aCount` + `bCount`
);
like image 262
riyana Avatar asked Jul 24 '11 07:07

riyana


People also ask

How can I SUM two columns in MySQL?

MySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .

How do I SUM a column in a table in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do you add two columns in SQL?

You can add multiple columns to an SQL table using the ALTER TABLE syntax. To do so, specify multiple columns to add after the ADD keyword. Separate each column you want to add using a comma. Suppose that we want to add two columns called “salary” and “bio” to our existing “employees” table.


1 Answers

It is not possible to do that exactly, but you can create a view based on a query that combines them:

CREATE VIEW `my_wacky_view` AS
SELECT `number1`, `number2`, `number1` + `number2` AS `total`
FROM `test1`;

I would avoid actually storing the combined data in a table, unless you're going to be running lots of queries that will reference the combined data in their WHERE clauses.

like image 131
TehShrike Avatar answered Nov 06 '22 10:11

TehShrike