Home > Database > Mysql Tutorial > body text

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

王林
Release: 2023-08-24 11:13:02
forward
1409 people have browsed it

我们如何通过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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template