2014-06-10 135 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