Home  >  Article  >  Database  >  How can we subtract values ​​in MySQL table via LEFT JOIN?

How can we subtract values ​​in MySQL table via LEFT JOIN?

王林
王林forward
2023-08-24 11:13:021404browse

我们如何通过LEFT JOIN在MySQL表中减去值?

It can be understood through an example where there are two tables with some values ​​and we use LEFT JOIN to subtract these values. Here we use two tables with 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 store the current price and previous price of the product respectively. Now, by using LEFT JOIN, the following query will find the price difference between the same products stored in both 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)

The above is the detailed content of How can we subtract values ​​in MySQL table via LEFT JOIN?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete