How can we subtract values in MySQL table with the help of LEFT JOIN?


It can be understood with the help of an example in which two tables are having some values and we subtract the values with the help of LEFT JOIN. Here we are taking two tables having the following data −

mysql> Select * from value_curdate;
+----+----------+-------+
| Id | Product  | Price |
+----+----------+-------+
| 1  | Notebook | 100   |
| 2  | Pen      | 40    |
| 3  | Pencil   | 65    |
+----+----------+-------+
3 rows in set (0.00 sec)

mysql> Select * from value_prevdate;
+----+-----------+-------+
| Id | Product   | Price |
+----+-----------+-------+
| 1  | Notebook  | 85    |
| 2  | Pen       | 34    |
| 3  | Pencil    | 56    |
| 4  | Colors    | 65    |
| 5  | Fevistick | 25    |
+----+-----------+-------+
5 rows in set (0.00 sec)

The above two tables are having the current price and previous price of products respectively. Now the following query, by using LEFT JOIN, will find the difference in price between the same products stored in both the tables.

mysql> Select value_curdate.id, value_curdate.product, value_curdate.price as Curprice,value_prevdate.price as 'prevprice', value_curdate.price-value_prevdate.price as 'Difference' from value_curdate LEFT JOIN value_prevdate ON value_curdate.id = value_prevdate.id ;
+----+----------+----------+-----------+------------+
| id | product  | Curprice | prevprice | Difference |
+----+----------+----------+-----------+------------+
| 1  | Notebook | 100      | 85        | 15         |
| 2  | Pen      | 40       | 34        | 6          |
| 3  | Pencil   | 65       | 56        | 9          |
+----+----------+----------+-----------+------------+
3 rows in set (0.00 sec)

Updated on: 20-Jun-2020

687 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements