【发布时间】:2017-07-29 09:21:57
【问题描述】:
我有两张桌子,item 和 prices。
prices 表保存item 表中每个项目的价格。价格表中有一个名为counter 的额外字段 - 以周期性方式存储并递增一。因此,对于每个计数器,价格表中将有一组 N 行,其中 N 是项目表中的项目数。
CREATE TABLE `item` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
)
CREATE TABLE `prices` (
`id` bigint(9) NOT NULL AUTO_INCREMENT,
`price` float(10,2) NOT NULL,
`ts` datetime NOT NULL,
`counter` int(10) unsigned DEFAULT NULL,
`item_id` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ts` (`ts`),
KEY `counter` (`item_id`,`counter`) USING BTREE
) ENGINE=InnoDB
现在,我需要找出每件商品对应的最高价格(在任何特定日期)以及计数器值。
任何商品都可能有多行价格相同 - 需要选择第一个匹配项。
我已经尝试了以下查询。
SELECT p.id, p.counter, max.price
FROM prices AS p
JOIN (
SELECT item_id, MAX( price ) as price
FROM prices
WHERE ts
BETWEEN '2017-07-28 00:00:00'
AND '2017-07-28 23:59:59'
GROUP BY item_id
)
max
ON max.item_id = p.item_id
and p.price= max.price
这并没有给出预期的结果。
如何更正我的查询?
谢谢。
编辑 - 示例数据
select id, item_id, price,counter from prices order by item_id, price;
+-------+---------+-------+---------+
| id | item_id | price | counter |
+-------+---------+-------+---------+
| 30192 | 54 | 18.95 | 200 |
| 15061 | 54 | 19.15 | 100 |
| 7503 | 54 | 19.45 | 50 |
| 22598 | 54 | 19.75 | 150 |
| 30127 | 100 | 30.20 | 200 |
| 22569 | 100 | 30.35 | 150 |
| 15033 | 100 | 30.35 | 100 |
| 7460 | 100 | 30.90 | 50 |
| 15084 | 115 | 25.35 | 100 |
| 7533 | 115 | 25.65 | 50 |
| 22623 | 115 | 25.75 | 150 |
| 30152 | 115 | 26.20 | 200 |
+-------+---------+-------+---------+
需要得到如下输出。
id, item_id, price, counter
22598 1 19.75 150
7460 2 30.90 50
30152 3 26.20 200
ps:暂时忽略时间戳。
【问题讨论】:
-
This doesn't give the desired result....您当前的输出是什么?怎么错了? -
顺便说一下,价格浮动的可能性很小。这就是发明十进制的原因
-
请找到添加的示例数据和预期输出。