Search code examples
phpsqlsubtraction

query the first sql column to subtract the other column


I have this table in my sql and I want to use cus_count1 value to subtract cus_count2 value. I want to query it, but I am not sure how do I go about doing it.

+---------------------+------------+------------+
|        Time         | cus_count1 | cus_count2 |
+---------------------+------------+------------+
| 2015-12-21 08:28:44 |          1 |          0 |
| 2015-12-21 08:29:09 |          2 |          1 |
| 2015-12-21 08:29:23 |          3 |          1 |
| 2015-12-21 08:29:35 |          4 |          1 |
| 2015-12-21 08:29:49 |          4 |          2 |
| 2015-12-21 08:30:09 |          5 |          2 |
| 2015-12-21 08:30:17 |          6 |          2 |
+---------------------+------------+------------+

this is my php code:

<?php

    $server = "localhost";
    $user = "root";
    $password = "";
    $database = "";

    $connection = mysql_connect($server,$user,$password);
    $db = mysql_select_db($database,$connection);

    $query1 = "SELECT time,  cus_count1 - cus_count2 AS cus_flow FROM new_tbl_cus";
    $result1 = mysql_query($query1);

     while($row = mysql_fetch_assoc($result1))
     {


        $dataset1[] = array(strtotime($row['time'])*1000,$row['cus_flow']);
        //echo strtotime($row['time'])*1000;

    }
?>

Solution

  • Do you just want simple subtraction? If yes, you could just do:

    select time, cus_count1 - cus_count2 as finalvalue
    from tablename
    

    I guess you might be asking for something different, or is it really this what you are asking for? In the above statement, finalvalue is the artificial column name (aka alias) given to the calculated/derived column.