我有一张定义如下的所有销售表:
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
存储在单独的项目表中)并将它们插入单独的表格中。我怎样才能获得这些数据?我尝试过这样的查询:
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 | |
+-------------------+---------------------+------+-----+---------+-------+
答案 0 :(得分:4)
这是Stack Overflow上频繁出现的最大n组问题。
INSERT INTO lastsale (StoreID, Price, ItemID)
SELECT s1.StoreID, s1.Price, s1.ItemID
FROM saledata s1
LEFT OUTER JOIN saledata s2
ON (s1.Itemid = s2.Itemid AND s1.SaleDate < s2.SaleDate)
WHERE s2.ItemID IS NULL;