4
我定義的所有銷售的表像:SQL查詢來獲取所有不同的項目最新記錄表中的
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 | |
+-------------------+---------------------+------+-----+---------+-------+
感謝stackoverflow,及時發現 – sansknwoledge 2011-07-02 21:21:28