2014-06-10 144 views
0

对于下面的表格和数据,我试图获得小于当前时间戳的最高effective_from值,每个唯一brand/model组合 - 实际上是当前每件商品的价格。选择具有最大值(有条件)的唯一行

CREATE TABLE things 
(`id` int, `brand` varchar(1), `model` varchar(5), `effective_from` int, `price` int); 

INSERT INTO things 
(`id`, `brand`, `model`, `effective_from`, `price`) 
VALUES 
(1, 'a', 'red', 1402351200, 100), 
(2, 'b', 'red', 1402351200, 110), 
(3, 'a', 'green', 1402391200, 120), 
(4, 'b', 'blue', 1402951200, 115), 
(5, 'a', 'red', 1409351200, 150), 
(6, 'a', 'blue', 1902351200, 140), 
(7, 'b', 'green', 1402358200, 135), 
(8, 'b', 'blue', 1902358200, 155), 
(9, 'b', 'red', 1902751200, 200), 
(10, 'a', 'red', 1908351200, 210), 
(11, 'a', 'red', 1402264800, 660); 

到目前为止,我已经设法让我找当我添加条件的特定brand/model组合行,但不知道如何获取目前的价格对所有唯一的行组合。

SELECT * 
FROM things 
WHERE effective_from<UNIX_TIMESTAMP() 
AND brand='a' 
AND model='red' 
ORDER BY effective_from DESC 
LIMIT 1; 

如果当前时间戳是1402404432结果应该是如下:

(1, 'a', 'red', 1402351200, 100), 
(3, 'a', 'green', 1402391200, 120), 
(2, 'b', 'red', 1402351200, 110), 
(7, 'b', 'green', 1402358200, 135), 
+0

期望的结果是什么样子? – Strawberry

+0

我已添加预期结果。 – user2959229

+0

我打败了你;-) – Strawberry

回答

2

我想你在这之后是。否则提供建议...

SELECT x.* 
    FROM things x 
    JOIN 
    (SELECT brand 
      , model 
      , MAX(effective_from) max_effective_from 
     FROM things 
     WHERE effective_from <= UNIX_TIMESTAMP() 
     GROUP 
      BY brand 
      , model 
    ) y 
    ON y.brand = x.brand 
    AND y.model = x.model 
    AND y.max_effective_from = x.effective_from; 
+------+-------+-------+----------------+-------+ 
| id | brand | model | effective_from | price | 
+------+-------+-------+----------------+-------+ 
| 1 | a  | red |  1402351200 | 100 | 
| 2 | b  | red |  1402351200 | 110 | 
| 3 | a  | green |  1402391200 | 120 | 
| 7 | b  | green |  1402358200 | 135 | 
+------+-------+-------+----------------+-------+ 

SELECT UNIX_TIMESTAMP(); 
+------------------+ 
| UNIX_TIMESTAMP() | 
+------------------+ 
|  1402404432 | 
+------------------+ 
+0

为什么'JOIN'?内部查询给我我正在寻找的结果... – user2959229

+1

也许你也想要其他列。 – Strawberry