4

我有一个所有销售定义的表格,如下所示:

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

但是,我希望能够获得所有商品的最后销售价格(ItemIDs 存储在单独的商品表中)并将它们插入单独的表中。我怎样才能得到这些数据?我试过这样的查询:

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    |       | 
+-------------------+---------------------+------+-----+---------+-------+
4

1 回答 1

4

这是 Stack Overflow 上经常出现的最大每组问题。

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;
于 2010-05-06T03:51:15.813 回答