我有一个所有销售定义的表格,如下所示:
mysql> describe saledata;
+-------------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+-------+
| SaleDate | datetime | NO | | NULL | |
| StoreID | bigint(20) unsigned | NO | | NULL | |
| Quantity | int(10) unsigned | NO | | NULL | |
| Price | decimal(19,4) | NO | | NULL | |
| ItemID | bigint(20) unsigned | NO | | NULL | |
+-------------------+---------------------+------+-----+---------+-------+
我需要获取所有商品的最后销售价格(因为价格可能会发生变化)。我知道我可以运行如下查询:
SELECT price FROM saledata WHERE itemID = 1234 AND storeID = 111 ORDER BY saledate DESC LIMIT 1
但是,我希望能够获得所有商品的最后销售价格(ItemID
s 存储在单独的商品表中)并将它们插入单独的表中。我怎样才能得到这些数据?我试过这样的查询:
SELECT storeID, itemID, price FROM saledata WHERE itemID IN (SELECT itemID from itemmap) ORDER BY saledate DESC LIMIT 1
然后将其包装到插入中,但它没有得到正确的数据。是否可以运行一个查询来获取每个项目的最后价格并将其插入到定义如下的表中:
mysql> describe lastsale;
+-------------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+-------+
| StoreID | bigint(20) unsigned | NO | | NULL | |
| Price | decimal(19,4) | NO | | NULL | |
| ItemID | bigint(20) unsigned | NO | | NULL | |
+-------------------+---------------------+------+-----+---------+-------+