简体   繁体   中英

MySQL statement to get min value with max ID

I want to select the minimum value with the largest id. For example, I want to select Playstation because it has a larger id than Silly Puddy.

This is my sql statement:

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

I keep getting Silly Puddy returned for Toy. Any suggestions on what to do differently? Thanks in advance!

as soon as id unique - there is only one price for one id, no any "minimum" or "maximum", just one:

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

Try this query. This should do it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM