2014-12-30 54 views
0

我想選擇最大值最小的值。例如,我想選擇Playstation,因爲它的ID比Silly Puddy大。MySQL聲明以最大值獲取最小值ID

這是我的SQL語句:

SELECT *, max(id), min(price) 
FROM table 
group by type 
ORDER BY id DESC 


id  name     type  price 
123451 Park's Great Hits  Music  19.99 
123452 Silly Puddy    Toy   3.99 
123453 Playstation    Toy   3.99 

我不斷收到傻Puddy返回玩具。有什麼不同的建議嗎? 在此先感謝!

+1

你一直困惑。由於'id'是唯一的,你總是隻能找到一個值,當然,這是「最小值」,這也是「最大值」。 –

+0

如果您願意,請考慮遵循以下簡單的兩步操作步驟:1.如果您尚未這樣做,請提供適當的DDL(和/或sqlfiddle),以便我們可以更輕鬆地複製問題。 2.如果您尚未這樣做,請提供與步驟1中提供的信息相對應的所需結果集。 – Strawberry

回答

5

只要ID獨一無二的 - 只有一個價格,一個ID,沒有任何「最低」或「最高」,只有一個:

select * from table where id in (
SELECT max(id) 
FROM table as a 
where a.price = (select min(price) from table as b where a.type=b.type) 
group by type 
) as t 
+2

我瞭解在具有最低「價格」_的組中具有最大「id」的要求。這是整體上最大的'id'。 –

+0

@MichaelBerkowski在這裏你去 –

0

嘗試此查詢。這應該做到這一點。

select t4.* 

from 

`table` t4 

join 

( 

    select t2.type, max(t2.id) as id 
    from 
    `table` t2 join 
    (
     select type, min(price) as price 
     from 
     `table` t1 
     group by type 
    ) t3 on t2.type = t3.type and t2.price = t3.price 
    group by t2.type 

) t5 on t4.id = t5.id 
相關問題