44

I want to multiply 2 cells for each row and put the value of that in the last column called Total. Can this be done by a normal query?

Example:

Pieces | Price | Total
6      |   4   |  null // should be 24
2      |  10   |  null // should be 10
flipdoubt
  • 13,897
  • 15
  • 64
  • 96
Arne Nouwynck
  • 495
  • 1
  • 4
  • 6

4 Answers4

93

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable
Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
Prescott
  • 7,312
  • 5
  • 49
  • 70
11

You can do it with:

UPDATE mytable SET Total = Pieces * Price;
vbence
  • 20,084
  • 9
  • 69
  • 118
8

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

Nanne
  • 64,065
  • 16
  • 119
  • 163
  • Sorry, I thought it was self-explanatory when you start your query with `INSERT`. Anyways, if you make an edit I can undo the downvote. – vbence Apr 17 '11 at 12:06
  • I did an edit, but if you leave a comment, the writer gets a notification. Now it was just luck I happend to notice the -2. :D – Nanne Apr 17 '11 at 12:07
-2

this was my solution:

i was looking for how to display the result not to calculate...

so. in this case. there is no column TOTAL in the database, but there is a total on the webpage...

 <td><?php echo $row['amount1'] * $row['amount2'] ?></td>

also this was needed first...

<?php 
   $conn=mysql_connect('localhost','testbla','adminbla');
mysql_select_db("testa",$conn);

$query1 = "select * from info2";
$get=mysql_query($query1);
while($row=mysql_fetch_array($get)){
   ?>
tijnn
  • 406
  • 1
  • 8
  • 24