可以通过一个示例来理解,在该示例中,两个表具有一些值,然后借助LEFT JOIN减去这些值。这里我们拿两个表,其中包含以下数据-
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)
上面两个表分别具有产品的当前价格和先前价格。现在,以下查询通过使用LEFT JOIN查找存储在两个表中的相同产品之间的价格差异。
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)