MySQL语句以获取具有最大ID的最小值

时间:2014-12-30 21:56:46

标签: mysql sql

我想选择ID最大的最小值。例如,我想选择Playstation,因为它的ID大于Silly Puddy。

这是我的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

我一直让Silly Puddy回归玩具。关于做什么不同的任何建议? 提前谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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