MySQL中最新的群组条目

时间:2016-01-26 23:26:30

标签: mysql sql

我有两张桌子:物品和价格

价格是项目的不同时间戳的价格集合(在本例中为24)

prices

项目包含所有项目的说明

items

我现在想要查询每个商品的最新价格的名称,销售价格,购买价格,优惠数量,需求数量和两个ID。

我目前的解决方案

SELECT items.id as id, items.icon as icon, items.name AS name, prices.sell as sell, prices.buy as buy, prices.demand as demand, prices.offer as offer, prices.timestamp as timestamp
FROM items JOIN prices ON prices.itemID = items.id
WHERE buy < 100000
  AND sell < 100000
  AND demand > 10000
  AND offer > 10000
  AND timestamp IN (SELECT MAX(timestamp) FROM prices AS p WHERE p.id = prices.id)
GROUP BY items.id
ORDER BY sell / buy
DESC LIMIT 25

根本不起作用(行似乎是随机的,但它们肯定不是最新的)。

2 个答案:

答案 0 :(得分:0)

看了我糟糕的照片后,我意识到解决方案就在我面前。而不是需要分组我可以使用items.lastupdate来选择合适的价格行

FROM items JOIN prices ON prices.itemID = items.id AND prices.timestamp = items.lastupdate

答案 1 :(得分:0)

SELECT i.id, i.icon, i.name, p.sell, p.buy, p.demand, p.offer, p.`timestamp`
FROM items i, prices p, (
    SELECT itemID, max(`timestamp`) max_ts
    FROM prices
    WHERE buy < 100000 AND sell < 100000 AND demand > 10000 AND offer > 10000
    GROUP BY 1
) as last_p
WHERE i.id = p.itemID
AND p.itemID = last_p.itemID AND p.`timestamp` = last_p.max_ts

如果您将以下WHERE放在子查询的内部或外部,结果可能会有所不同,这取决于您的实际情况:

WHERE buy < 100000 AND sell < 100000 AND demand > 10000 AND offer > 10000