我在两个不同的表中有价格,想将它们相减(当前价格-当天价格)并以DESC形式订购它们。我想知道是否可以使用单个MySQL命令来完成。
表结构
Table 1 id | Item Name | Date | Price 1 | alpha | 2011-10-05 | 10 2 | beta | 2011-10-05 | 12 3 | gamma | 2011-10-05 | 14 Table 2 id | Item Name | Date | Price 1 | alpha | 2011-10-04 | 8 2 | beta | 2011-10-04 | 10 3 | gamma | 2011-10-04 | 12 4 | alpha | 2011-10-03 | 4 5 | beta | 2011-10-03 | 6 6 | gamma | 2011-10-03 | 8
SELECT table1.id, table1.`Item Name`, table1.`Date` AS CurrDate, table1.Price AS CurrPrice, table2.`Date` AS PrevDate, table2.Price AS PrevPrice, table1.Price - table2.Price AS Difference FROM table1 LEFT JOIN table2 ON table1.id = table2.id AND table1.`Date` - INTERVAL 1 DAY = table2.`Date` ORDER BY Difference DESC
除了我使用LEFT JOIN的方式外,此查询没有什么特别的。我相信,如果无法提供昨天的记录价格,则最后三列将包含NULL。输出:
id | Item Name | CurrDate | CurrPrice | PrevDate | PrevPrice | Difference 2 | beta | 2011-10-05 | 12 | 2011-10-04 | 10 | 2 3 | gamma | 2011-10-05 | 14 | 2011-10-04 | 12 | 2 1 | alpha | 2011-10-05 | 10 | 2011-10-04 | 8 | 2